Php 带递归的Foreach
我创建了一个函数,用于计算类别及其子类别中的所有唯一帖子(唯一,因为某些帖子可能属于少数几个不同类别) 但我知道这是不准确的代码。 请帮我按正确的方式建造它。因此,它将接受无限级别的子类别 事先非常感谢你 这是我的代码:Php 带递归的Foreach,php,arrays,laravel,recursion,foreach,Php,Arrays,Laravel,Recursion,Foreach,我创建了一个函数,用于计算类别及其子类别中的所有唯一帖子(唯一,因为某些帖子可能属于少数几个不同类别) 但我知道这是不准确的代码。 请帮我按正确的方式建造它。因此,它将接受无限级别的子类别 事先非常感谢你 这是我的代码: public function countAllCatPosts($category, $postIds = array()){ $catPosts = $category->posts->pluck('id')->toArr
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;
}
$category
是laravel模型实例吗?如果它是一个模型,它是否与相同的模型有关系,如parent\u id
?是的,它是laravel模型实例。但它如何帮助我需要计算每个子类别中所有独特的帖子。并将total返回到顶级类别。约翰·泰纳的答案是有效的。或者你有另一个没有foreach循环的更好的选择?太好了!非常感谢你。这有帮助。工作得很有魅力!你犯了一个小错误,但我已经改正了。getChildren()函数中的foreach($children->categories as$childCategory)应该是foreach($children->categories as$childCategory),而不是foreach($childCategory)。再次感谢你!你为我节省了很多时间。你能不能看看另一个类似情况的问题?如果你能帮忙,我会很高兴的。非常感谢。