亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過生成列布局來輸出 foreach 內的元素?

如何通過生成列布局來輸出 foreach 內的元素?

PHP
烙印99 2022-08-05 10:47:42
我有一個問題需要解決。我在PHP中有這個HTML布局:<div class="container">    <div class="wrapper">        <span class="entry"></span>        <span class="entry"></span>    </div>    <div class="wrapper">        <span class="entry"></span>        <span class="entry"></span>    </div>    <div class="wrapper">        <span class="entry"></span>        <span class="entry"></span>    </div>    <div class="wrapper">        <span class="entry"></span>        <span class="entry"></span>    </div></div>我在這里有一個列布局。這意味著我總是想將2個元素打包到一個包裝器類中。我從數組中獲取所有元素,我想用循環輸出。我的想法是每2次傳遞一次才輸出包裝器,但這會產生以下輸出:<div class="wrapper">    <div class="wrapper">        <span class="entry"></span>    </div>    <span class="entry"></span>    <div class="wrapper">        <span class="entry"></span>    </div>    <span class="entry"></span>    <div class="wrapper">        <span class="entry"></span>    </div>    <span class="entry"></span>    <div class="wrapper">        <span class="entry"></span>    </div>    <span class="entry"></span></div>這是我的代碼:<div class="container">    <?php    $loop_count = 0;    foreach ( $array as $item ) {        if ( $loop_count % 2 === 0 ) { ?>            <div class="wrapper">        <?php } ?>        <span class="entry"><?= $item ?></span>        <?php if ( $loop_count % 2 === 0 ) { ?>            </div>        <?php }        $loop_count++;    } ?></div>我在圖像中的預期輸出:
查看完整描述

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>


查看完整回答
反對 回復 2022-08-05
  • 1 回答
  • 0 關注
  • 107 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號