我试图将内容打印成三列,这意味着我需要检索与术语3n-2匹配的记录。我该怎么做..。也许用模数?谢谢!
foreach($grid as $tile):
echo '<div class="tile"><img src="/media/full/' . $tile['source'] . '"/></div>';
endforeach;发布于 2015-01-08 19:31:35
我想你要找的只是一个额外的柜台:
$i=0;
foreach($grid as $tile) {
if($i++ % 3 == 0) {
//do something every 3rd time
}
//do something every time
}发布于 2015-01-08 19:36:55
我想你是在寻找这样的东西:
(示例代码,只需使用$arr更改$grid)
<?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
for($count = 0; $count < count($arr); $count++) {
if($count % 3 == 0 && $count != 0)
echo "<br />";
echo $arr[$count];
}
?>输出:
123
456
789或者,如果希望将列放在单独的数组中:
<?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$columnOne = array();
$columnTwo = array();
$columnThree = array();
for($count = 0; $count < count($arr); $count++) {
if($count % 3 == 0)
$columnOne[] = $arr[$count];
elseif($count % 3 == 1)
$columnTwo[] = $arr[$count];
else
$columnThree[] = $arr[$count];
}
print_r($columnOne);
print_r($columnTwo);
print_r($columnThree);
?>输出:
Array ( [0] => 1 [1] => 4 [2] => 7 )
Array ( [0] => 2 [1] => 5 [2] => 8 )
Array ( [0] => 3 [1] => 6 [2] => 9 )发布于 2015-01-08 19:32:55
是的,如果我正确理解您的意思,我将使用模php操作符%:
<?php
$grid = array(1,2,3,4,5,6,7); # just for testing
$n = 1;
foreach($grid as $tile) {
if (($n + 2) % 3 == 0) {
#echo '<div class="tile"><img src="/media/full/' . $tile['source'] . '"/></div>';
echo "$n\n"; # just for testing
}
$n++;
}
?>它产生:
$ php x.php
1
4
7https://stackoverflow.com/questions/27848030
复制相似问题