为了账号安全,请及时绑定邮箱和手机立即绑定

PHP - 从 foreach 中删除重复项

PHP - 从 foreach 中删除重复项

PHP
慕森王 2021-11-05 12:45:34
在 Magento 中,我有一个包含产品的数组,我想从这些产品中获得它们所在的类别。这就是我所拥有的,但我正在使用 foreach 来浏览产品,因此需要删除重复项.我已经有了 foreach 的类别名称,但是现在需要删除一些重复项。<?php foreach ($_productCollection as $_product): ?>    <div class="bk-all-products">        <?php            $bk_product_id = $_product->getCategoryIds();             $bk_category_id = $bk_product_id[1];            $categoryId = $bk_category_id;            $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();            $category = $_objectManager->create('Magento\Catalog\Model\Category')            ->load($categoryId);            $bk_category_id_name = $category->getName();            echo $bk_category_id_name;            echo "<br><br>";        ?>    </div><?php endforeach; ?>附加信息当我还在 foreach 中打印数组时,这就是返回值:数组 ( [0] => 354 [1] => 362 [2] => 360 [3] => 414) Cafeïnevrije koffie数组 ( [0] => 354 [1] => 362 [2] => 364 [3] => 414) Cafeïnevrije koffie数组 ( [0] => 354 [1] => 367 ) Koffiepakketten数组 ( [0] => 354 [1] => 364 )数组 ( [0] => 354 [1] => 360 ) 浓缩咖啡数组([0] => 354 [1] => 360 [2] => 414)Espressokoffie数组([0] => 354 [1] => 364 [2] => 414)数组([0] => 354 [1] => 360 [2] => 414)Espressokoffie数组 ( [0] => 354 [1] => 367 ) Koffiepakketten数组 ( [0] => 354 [1] => 367 ) Koffiepakketten数组 ( [0] => 367 [1] => 354 )数组 ( [0] => 367 [1] => 354 )
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

最简单的方法是将已经显示的类别存储在 an 中,Array并使用in_array检查您要显示的类别是否已经在其中


编辑:存储 id 可能比存储名称更好,因为如果已经获取,您可以避免获取名称:


<?php

$diplayed_categories = []; //initializing array

foreach ($_productCollection as $_product):

?>

    <div class="bk-all-products">

        <?php

            $bk_product_id = $_product->getCategoryIds(); 

            $bk_category_id = $bk_product_id[1];


            if(!in_array($bk_category_id, $diplayed_categories)){ //testing if not in array

                $diplayed_categories[] = $bk_category_id; //filling the array


                //moved inside the if, no need to fetch it again if it exists

                //$categoryId = $bk_category_id; //useless var

                $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

                $category = $_objectManager->create('Magento\Catalog\Model\Category')

                  ->load($bk_category_id); //replaced by $bk_category_id

                $bk_category_id_name = $category->getName();


                echo $bk_category_id_name;


                echo "<br><br>";

            }

        ?>

    </div>

<?php endforeach; ?>


查看完整回答
反对 回复 2021-11-05
  • 1 回答
  • 0 关注
  • 262 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信