我有一个简单的foreach循环,可以输出我想要的信息。
但是,我想用每两个结果包装一个div。 我尝试使用模数运算符没有成功(结果应用于每个结果)。
所以,我的代码:
foreach ($result->data as $info) {
// A open div to wrap two results
echo 'something';
// An closing div to wrap the previous two results
}
答案 0 :(得分:1)
这样就可以了!
foreach ($result->data as $i=>$info) {
if ($i % 2 == 0) echo '<div>';
echo $info;
if ($i % 2 == 1) echo '</div>';
}
if (count($result->data) % 2 == 1) echo '</div>';
正是你所问的;)
答案 1 :(得分:0)
添加索引计数,然后检查它在代码中可以被2整除。 在这种情况下,if块需要位于foreach循环的顶部,因为我在0处开始$ i。请停止编辑该部分:)
$i = 0;
// Create first new div before loop, here.
echo '<div>'; //first div
foreach ($result->data as $info) {
// An closing div to wrap the previous two results
if ($i % 2){
// Code here would occur after each two iterations
// IE: close div then open new one. something like this
echo '</div><div>';
}
// A open div to wrap two results
echo 'something';
$i++;
}
// close final div after loop, here.
echo '</div>';
答案 2 :(得分:0)
最简单的方法:迭代2步。
for ($cc = 0; $cc<count($result->data); $cc += 2) {
// here >> start div container for both
echo $result->data[$cc];
if (defined($result->data[$cc+1]))
echo $result->data[$cc+1];
// here >> end div container for both
}
为了清晰而省略了HTML。
如果结果包含奇数个项目,您还可以添加else分支以输出占位符。
答案 3 :(得分:0)
要从数组中输出每两个结果,您也可以使用
<?php
$array = range( 1, 20 );
foreach( array_chunk( $array, 2 ) as $pair ) {
echo '<div>' , implode( ' ', $pair ) , '</div>';
}
// <div>1 2</div>
// <div>3 4</div>
// etc
?>
答案 4 :(得分:-1)
设置2个变量,string和int
如果int变量的值不是偶数,则将值保存在字符串变量中
当第二个变量是偶数时
换行div
答案 5 :(得分:-1)
//只是
<?php
foreach($result->data as $i=>$info){
if($i<5){
echo $info
}
}
?>