PHP: 每 2 个结果回显一些东西

PHP: Echo something for each 2 results

我有一个简单的 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
}

添加一个索引计数,然后在代码中检查它是否可以被 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 为步长进行迭代。

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 分支以输出占位符。

设置 2 个变量,string 和 int
如果int变量的值不是偶数
,则将值保存在字符串变量中 当第二个变量为偶数时
包裹在 div

这样就可以了!

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>';

正是你问的 ;)

要从数组中输出每两个结果,您还可以使用

<?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

?>

//简单

<?php 
   foreach($result->data as $i=>$info){
     if($i<5){
        echo $info
}
}          
 ?>