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 關注
- 107 瀏覽
添加回答
舉報