如何解决带递归的foreach
我创建了一个函数,用于计算类别及其子类别中的所有 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;
}
解决方法
不确定这是否是您所追求的
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。