【发布时间】:2021-07-29 23:06:02
【问题描述】:
我创建了一个函数来计算类别及其子类别中的所有 UNIQUE 帖子(UNIQUE,因为有些帖子可以属于几个不同的类别)。
但我知道这是不准确的代码。 请帮助我以正确的方式构建它。所以它将接受无限级别的子类别。
非常感谢您。
这是我的代码:
public function countAllCatPosts($category, $postIds = array()){
$catPosts = $category->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
foreach($category->categories as $childCategory){
$catPosts = $childCategory->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
foreach($childCategory->categories as $childCategory1){
$catPosts = $childCategory1->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
foreach($childCategory1->categories as $childCategory2){
$catPosts = $childCategory2->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
foreach($childCategory2->categories as $childCategory3){
$catPosts = $childCategory3->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
}
}
}
}
$total = count(array_unique($postIds));
return $total;
}
【问题讨论】:
-
is
$category是 laravel 模型实例吗?如果是模型,是否与parent_id等同一模型有关系? -
是的,它是 laravel 模型实例。但它如何帮助我需要计算每个子类别中的所有独特帖子。并将总计返回到最顶级的类别。 John Tyner 的回答是有效的。或者也许你有另一个更好的选择,没有 foreach 循环?
标签: php arrays laravel recursion foreach