首页 > 解决方案 > 从 N 长度数组中每个循环获取 2 个元素

问题描述

我见过类似的问题,但我觉得我的问题不同,我有一个 2 列页面,每行需要 2 个用户,问题是当我有一个奇数长度的数组时,最后一个元素没有出现在这里是我的逻辑

<?php for($i = 0; $i < count($team); $i++){
      echo "Looping ".$i;  
      ?>
      <div class="row">
             <?php for($z = $i; $z < 2; $z++){
              echo "inner Looping ".$z?>
            <div class="col s12 m6 grid">
              <figure class="effect-honey">
                <img src="<?php echo  $team[$z]['image']; ?>" alt="<?php echo  $team[$z]['fname']. ' '.$team[$z]['lname']; ?>"/>
                <figcaption>
                  <h2><?php echo  $team[$z]['fname']; ?><span><?php echo  $team[$z]['lname']; ?></span> <i><?php echo  $team[$z]['position']; ?></i></h2>
                </figcaption>     
              </figure>
            </div>
          <?php $i = $z;} ?>
          </div>
      <?php } ?>
      </div>

包含 3 个项目的数组的输出样本

标签: phparrays

解决方案


使用array_chunk()on $teamwith2作为块大小参数。然后,您可以使用外部foreach()来迭代生成的对,使用内部foreach()来显示子数组。

假设您不需要在奇数场景中为缺少的第二个元素编写空的 html 元素,这里有一个实现(有几种方法可以做到这一点)。

代码(演示

$team = [
    ['image' => 'A.jpg', 'fname' => 'B', 'lname' => 'C', 'position' => 'D'],
    ['image' => 'E.jpg', 'fname' => 'F', 'lname' => 'G', 'position' => 'H'],
    ['image' => 'I.jpg', 'fname' => 'J', 'lname' => 'K', 'position' => 'L']
];
$pairs = array_chunk($team, 2);
foreach ($pairs as $pair) {
    echo "<div class=\"row\">";
        foreach ($pair as $player) {
            echo "<div class=\"col s12 m6 grid\">";
                echo "<figure class=\"effect-honey\">";
                    echo "<img src=\"{$player['image']}\" alt=\"{$player['fname']} {$player['lname']}\"/>";
                    echo "<figcaption>";
                        echo "<h2>{$player['fname']}<span>{$player['lname']}</span> <i>{$player['position']}</i></h2>";
                    echo "</figcaption>";
                echo "</figure>";
            echo "</div>";
        }
    echo "</div>";
}

输出:

<div class="row">
    <div class="col s12 m6 grid">
        <figure class="effect-honey">
            <img src="A.jpg" alt="B C"/>
            <figcaption>
                <h2>B<span>C</span> <i>D</i></h2>
            </figcaption>
        </figure>
    </div>
    <div class="col s12 m6 grid">
        <figure class="effect-honey">
            <img src="E.jpg" alt="F G"/>
            <figcaption>
                <h2>F<span>G</span> <i>H</i></h2>
            </figcaption>
        </figure>
    </div>
</div>
<div class="row">
    <div class="col s12 m6 grid">
        <figure class="effect-honey">
            <img src="I.jpg" alt="J K"/>
            <figcaption>
                <h2>J<span>K</span> <i>L</i></h2>
            </figcaption>
        </figure>
    </div>
</div>

如果您在缺少“右侧”播放器时需要 html 的空白(保留空间)部分,请澄清您的问题/所需的结果。


推荐阅读