php - Foreach - 包含<li> </ li>,里面有两个结果,然后重复.

Dan*_*ers 3 php arrays foreach counter html-lists

使用php - 我试图在数组上运行"foreach",但我想将每两个结果包装在li标签中.输出将如下所示.

<li>

<div>result 1</div>

<div>result 2</div>

</li>

<li>

<div>result 3</div>

<div>result 4</div>

</li>

<li>

<div>result 5</div>

<div>result 6</div>

</li>

我该怎么做呢?

谢谢!

she*_*sek 9

$chunks = array_chunk($arr, 2);
foreach ($chunks as $chunk) {
    // $chunk could have either 2 elements, or just one on the last iteration on an array with odd number of elements
    echo '<li>';
    foreach ($chunk as $value) {
        echo '<div>' . $value . '</div>';
    }
    echo '</li>';
}
Run Code Online (Sandbox Code Playgroud)