php - 从 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>
解决方案
使用array_chunk()
on $team
with2
作为块大小参数。然后,您可以使用外部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 的空白(保留空间)部分,请澄清您的问题/所需的结果。
推荐阅读
- c# - Xamarin.Forms:处理导航工具栏按钮(Shell)
- vue.js - 在不同的地方使用相同的 Vue 变量会出错
- c# - 如何在不重复枚举名称的情况下使用枚举?
- flutter - 哎呀;颤振意外退出:“第 8 行第 2 列错误:预期为 ':'
- mysql - 无法读取未定义的属性“connectionConfig”
- postgresql - Docker 和 Postgres - 使用 5432 以外的端口时服务器意外关闭连接错误
- reactjs - Dockerfile 卡在 Jenkins 的 npm install 上
- excel - Div / 0 替换循环的 VBA 问题
- java - 将域和端口映射到 DNS
- api - 如何通过电报数字用户 ID 查找或发送消息?