递归的 Foreach
Posted
技术标签:
【中文标题】递归的 Foreach【英文标题】:Foreach with recursion 【发布时间】: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 循环?
【参考方案1】:
不确定这是不是你想要的
public function countAllCatPosts($category, $postIds = array())
$postIds = $this->getChildren($category, $postIds);
$total = count(array_unique($postIds));
return $total;
public function getChildren($children, $postIds)
$catPosts = $children->posts->pluck('id')->toArray();
$postIds = array_merge($postIds, $catPosts);
foreach($children->categories as $childCategory)
$postIds = $this->getChildren($childCategory, $postIds);
return $postIds;
【讨论】:
太棒了!太感谢了。它有帮助。像魅力一样工作!你犯了一个小错误,但我已经改正了。 getChildren() 函数中的 foreach($catPosts as $childCategory) 应该是 foreach($children->categories as $childCategory),而不是 foreach($catPosts as $childCategory)。再次感谢你!你为我节省了很多时间。 你能看看另一个类似情况的问题吗***.com/questions/67452861/… 如果你能提供帮助,我会很高兴。谢谢。以上是关于递归的 Foreach的主要内容,如果未能解决你的问题,请参考以下文章