首页 > 解决方案 > 在每次最后一次出现数组值后打印新行

问题描述

我有一个 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>每个产品之后。

解决这个问题的最佳方法是什么?谢谢!

标签: phparrays

解决方案


应该做的伎俩:

<?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/>";
?>

推荐阅读