3 回答

TA贡献1853条经验 获得超6个赞
阅读您的问题看起来更多 ProductSubCategory 属于 ProductCategory 对象而不是 Product 对象。
基本上,我相信你可以通过Product一个ProductCategory对象和ProductCategory一个数组来更好地设计它ProductSubCategory。因此,当您获得Product对象时,您可以访问它ProductCategory和所有ProductSubCategory对象。
所以,你可以像这样迭代你的对象:
foreach($allProducts as $product) {
$category = $product->getCategory(); // Get your object category
$subCategories = $category->getSubCategories(); // Get your sub categories from CategoryObject
echo "Category: " . $category;
foreach($subCategories as $subCategory) {
echo "Sub category: " . $subCategory;
}
}
您可以在上面的问题中得到您期望的结果。

TA贡献1793条经验 获得超6个赞
您可以在一个循环中执行此操作:
$allCategories = [];
foreach($allProducts as $product){
if(!isset($allCategories[$product->category)) // add the category
$allCategories[$product->category] = [];
if(!isset($allCategories[$product->category][$product->subcategory])) // add the subcategory to top-level category
$allCategories[$product->category][] = $product->subcategory;
}

TA贡献1995条经验 获得超2个赞
我假设有一个函数可以获取给定类别的所有子类别
$categories = 数组();
$allProducts = $this->get_all_products();
foreach ( $allProducts as $key => $item ) {
$categories[$key][] = $item->category;
foreach ($this->get_all_subcategories($item->category) as $subCat) { //假设有一个 get_all_subcategories 函数可用,它可以是一个以 category 为 key 和 subcategories 为 value 的数组
$categories[$key][] = $subCat;
}
}
打印_r($类别);
修改
$categories = 数组();
$allProducts = $this->get_all_products();
foreach ( $allProducts as $key => $item ) {
$categories[$key][0] = $item->category;
if (!in_array($item->subcategory, $categories[$key]))
$categories[$key][] = $item->subcategory;
}
打印_r($类别);
- 3 回答
- 0 关注
- 157 浏览
添加回答
举报