带递归的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;
}