我想让它每3列形成一个新行。我迷路了,即使在阅读其他帖子后也无法弄清楚如何做到这一点。所以我想让它像是
图标图标图标
图标图标图标
图标图标图标
等....
foreach($sMenu as $row) {
$sClass = ($row['id'] == $aPage['id']) ? ' class="ui-btn-active ui-btn-custom"' : ' class="ui-btn-custom"';
$sIcon = ($row['icon'] != '') ? ' data-icon="' . $row['icon'] . '"' : '';
$sSiteRoot = get('site-root');
$row['url'] .= ($row['url'] == '') ? '' : '/';
$url = $sSiteRoot . $row['url'];
$url = str_replace('(', '%28', $url);
$url = str_replace(')', '%29', $url);
$url = str_replace("'", '%27', $url);
$sNavigation2 .= '<td><img src=". $sIcon .' . $url . '"></td>';
}
答案 0 :(得分:5)
有时,最简单的方法是让变量跟踪运行此循环的次数。例如:
$i = 0;
然后,在循环内部,只需检查数字$i
是否等于2(在这种情况下)。
foreach($sMenu as $row) {
// this is all your old code right here...
if ($i == 2) {
// then add your </tr><tr> break or whatever...
$i = 0;
} else {
$i++;
}
}
然后,继续经历foreach循环。
这也可以使用modulus operator作为编写此“划线”检查的更简洁方法来完成(如此处的其他答案所示。)
答案 1 :(得分:2)
如果计数器可被3整除,则使用modulus(%)并输出新行:
$i = 0;
foreach($sMenu as $row) {
$i += 1;
$sClass = ($row['id'] == $aPage['id']) ? ' class="ui-btn-active ui-btn-custom"' : ' class="ui-btn-custom"';
$sIcon = ($row['icon'] != '') ? ' data-icon="' . $row['icon'] . '"' : '';
$sSiteRoot = get('site-root');
$row['url'] .= ($row['url'] == '') ? '' : '/';
$url = $sSiteRoot . $row['url'];
$url = str_replace('(', '%28', $url);
$url = str_replace(')', '%29', $url);
$url = str_replace("'", '%27', $url);
$sNavigation2 .= '<td><img src=". $sIcon .' . $url . '"></td>';
if( $i % 3 == 0 ) {
$sNavigation2 .= '</tr><tr>';
}
}
答案 2 :(得分:0)
你可以使用&#34;键&#34;作为数组中的索引:
foreach($sMenu as $index=>$row)
{
if(($index)%3==0){$sNavigation2 .= "<tr>";}
//$sClass = ($row['id'] == $aPage['id']) ? ' class="ui-btn-active ui-btn-custom"' : ' class="ui-btn-custom"';
//$sIcon = ($row['icon'] != '') ? ' data-icon="' . $row['icon'] . '"' : '';
//$sSiteRoot = get('site-root');
//$row['url'] .= ($row['url'] == '') ? '' : '/';
//$url = $sSiteRoot . $row['url'];
//$url = str_replace('(', '%28', $url);
//$url = str_replace(')', '%29', $url);
//$url = str_replace("'", '%27', $url);
//$sNavigation2 .= '<td><img src=". $sIcon .' . $url . '"></td>';
if(($index+1)%3==0){$sNavigation2 .= "</tr>";}
}
if(count($sMenu)%3 != 2){$sNavigation2 .= "</tr>";}
答案 3 :(得分:0)
检查每三个项目的一种方法是使用the modulo operator,它会在分割时检查剩余部分。
这里有一些让你开始的伪代码:
$counter = 0;
// start the first row
$html = '<tr>';
foreach( $sMenu as $row) {
//add an item
$html .= '<td>' . $row[ 'id' ] . '</td>';
//increment the counter, which is used to keep track of the number of items
$counter++;
//if $counter/3 has zero as a remainder, it's divisible by three
if( $counter % 3 === 0 ) {
//end the row after 3 items and begin a new one
$html .= '</tr><tr>';
}
}
//make sure there's an ending <tr> in case it ended on an odd number of items
$html = preg_replace( '/<tr>$/gi', '', $html );
$html .= '</tr>';