1 回答
TA贡献1828条经验 获得超3个赞
你的代码会有点复杂:
<?php
$array = [1,2,3];?>
<div class="container">
<?php
$loop_count = 0;
foreach ( $array as $item ) {
// here you open `div.wrapper`
if ( $loop_count % 2 === 0 ) { ?>
<div class="wrapper">
<?php } ?>
<span class="entry"><?= $item ?></span>
<?php
// here you close `div.wrapper`
if ( $loop_count % 2 === 1 ) { ?>
</div>
<?php }
$loop_count++;
}
// here you close `div.wrapper` if you have odd count of elements
if ( $loop_count % 2 === 1 ) { ?>
</div>
<?php }?>
</div>
不太复杂的解决方案是将数组拆分为大小为 2 的块:
<?php
$array = [1,2,3,4];
$chunks = array_chunk($array, 2);
?>
<div class="container">
<?php
foreach ( $chunks as $chunk ) {?>
<div class="wrapper">
<span class="entry"><?= $chunk[0] ?></span>
<!-- Here you can check if second element exists -->
<span class="entry"><?= $chunk[1] ?></span>
</div>
<?php }?>
</div>
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报