php - 在每次最后一次出现数组值后打印新行
问题描述
我有一个 php 数组,我需要在每次出现后打印一个新的换行符,它的外观如下:
Array (
[0] => Array (
[productid] => 2
[productname] = "Product A"
[categoryid] => 1
)
[1] => Array (
[productid] => 4
[productname] = "Product B"
[categoryid] => 2
)
[2] => Array (
[productid] => 4
[productname] = "Product C"
[categoryid] => 2
)
[3] => Array (
[productid] => 4
[productname] = "Product D"
[categoryid] => 3
)
[4] => Array (
[productid] => 4
[productname] = "Product E"
[categoryid] => 3
)
)
所以我像这样遍历我的产品:
<?php foreach ($products as $index => $product) {
echo "<div class='column'>";
echo "$product->productname";
echo "</div>";
/* TODO: Echo br element for each new categoryid */
}?>
这很好用,并给了我 HTML 输出:
<div class="column">
Product A
</div>
<div class="column">
Product B
</div>
<div class="column">
Product C
</div>
<div class="column">
Product D
</div>
<div class="column">
Product E
</div>
但是,我需要<br>
为每个新类别强制一个新行,因此我的 HTML 输出将变为:
<div class="column">
Product A
</div>
<br> <!-- Breakline because this is the last item in this categoryid -->
<div class="column">
Product B
</div>
<div class="column">
Product C
</div>
<br> <!-- Breakline because this is the last item in this categoryid -->
<div class="column">
Product D
</div>
<div class="column">
Product E
</div>
<br> <!-- Breakline because this is the last item in this categoryid -->
我想我可以跟踪上次使用的 categoryid,如果在我的 foreach 开始时它不一样,则回显:
if ($lastProductCategory == $products->categoryid) { echo '<br'>};
在 foreach 结束时:
$lastProductCategory = $products->categoryid;
但这不适用于第一项,因为 $lastProductCategory 尚未设置,但如果我移动 $lastProductCategory 定义的位置,它现在插入<br>
每个产品之后。
解决这个问题的最佳方法是什么?谢谢!
解决方案
应该做的伎俩:
<?php
$lastId = null;
foreach ($products as $index => $product) {
if ($lastId !== null && $lastId !== $product->categoryid) { // Probably should be $product['categoryid'], but assuming $product->productname is correct then this should be too
echo "<br/>";
}
$lastId = $product->categoryid; // Probably should be $product['categoryid'], but assuming $product->productname is correct then this should be too
echo "<div class='column'>";
echo $product->productname; // Not sure why its not $product['productname'], but you said it works :x
echo "</div>";
}
echo "<br/>";
?>
推荐阅读
- google-maps - flutter_google_maps 屏幕坐标到地图坐标
- java - 从私有和公共 maven/sbt 工件存储库中获取依赖项
- php - PHP 7 是否有等价的 array_value_last()?
- tkinter - 我无法在 tkinter 的列表框中获取所选项目的索引值
- python - Panda 的 ExcelWriter 附加模式不起作用
- git - 如何在使用 git 命令行创建合并请求时传递目标分支
- kubernetes - 是否有在 kubernetes 中创建守护程序集的命令式命令?
- python - lru_cache 上的 Python 3 脚本崩溃
- python-3.x - 使用 Selenium 将浏览器窗口大小调整为屏幕的 50%
- python-3.x - 鼻子单元测试发现在python 3.8上被打破