在PHP中重新启动foreach循环

在PHP中重新启动foreach循环,php,foreach,Php,Foreach,我有一个数组,其中包含产品作为对象。每个对象都包含一个键=类别\标题 我有一个foreach循环,在我的例子中,$col=3在引导行中生成具有可配置列的产品 我需要的是,如果出现新的分类标题,我需要有一个新行 我创建了一个数组来推送其中所有的category\u标题,如果它是一个新的类别,则创建一个变量。但现在我被卡住了 foreach看起来像这样: <?php foreach($productspercat as $product): ?>

我有一个数组,其中包含产品作为对象。每个对象都包含一个键=类别\标题

我有一个foreach循环,在我的例子中,
$col=3
在引导行中生成具有可配置列的产品

我需要的是,如果出现新的分类标题,我需要有一个新行

我创建了一个数组来推送其中所有的
category\u标题
,如果它是一个新的类别,则创建一个变量。但现在我被卡住了

foreach看起来像这样:

<?php foreach($productspercat as $product):         ?>


            <!-- Make sure product is enabled and visible @front end -->
            <?php //  if($product->enabled && $product->visibility):?>
                <?php

                    $catnew = false;
                $categorytitle = $product->category_title;
                if(!in_array($categorytitle, $totalcategories, true)):?>
                    <?php               array_push($totalcategories,$categorytitle );
                    $catnew=true;
            ?>
                <?php endif;?>


如果不想刷新页面,可以使用jQuery或Angular JS。
通过jQuery,如果您想在start中添加数据,可以通过jQuery prepend()函数添加数据,也可以通过append()函数添加结束部分。


<?php 
// Arranged products by category title
$arrangedProducts = array()
foreach($productspercat as $product) {
    if (!array_key_exists($product->category_title, $arrangedProducts)) {
        $arrangedProducts[$product->category_title] = array();
    }

    $arrangedProducts[$product->category_title][] = $product;
}

// each category is a key and its value is an array with all its products
foreach ($arrangedProducts as $categoryTitle => $products) {
    // you create a new row
    // ....
    foreach ($products as $product) {
        // you display product information
    }

    // you end the row
}
?>

在php脚本中必须有一种方法可以做到这一点。只有我是php新手。我相信答案很简单,但我的大脑因为各种可能而受到伤害:不要使用
foreach()
。它不是为重新启动而设计的,但是通过常规的
for
循环,您可以做任何您想做的事情。谢谢!出于某种原因,我现在只得到了3列中具有相同产品的1行。问题是只要类别中有产品,它就应该创建行,这就是$col的用途。它计算列数,然后(在我的例子3中)开始一个新行。在每个类别中,这应该保持不变,只有ist应该断开一行,如果剩下的产品较少(例如,类别中只有2个产品),它应该断开常规并开始新的一行。如果我正确理解了你的代码,它会为每个类别创建一行,这是不完全正确的。我明白了!我不得不重置外部foreach中的计数器,现在它正在工作!!谢谢你,你是我的英雄!!
<?php 
// Arranged products by category title
$arrangedProducts = array()
foreach($productspercat as $product) {
    if (!array_key_exists($product->category_title, $arrangedProducts)) {
        $arrangedProducts[$product->category_title] = array();
    }

    $arrangedProducts[$product->category_title][] = $product;
}

// each category is a key and its value is an array with all its products
foreach ($arrangedProducts as $categoryTitle => $products) {
    // you create a new row
    // ....
    foreach ($products as $product) {
        // you display product information
    }

    // you end the row
}
?>