douluoqiu4538
2017-09-06 10:36
采纳率: 100%
浏览 442
已采纳

PHP - 用于查找任何给定父级的父级的递归函数 - 问题

I hope somebody can help, this is driving me crazy!

I have a simply recursive PHP function for getting all parents to any given parent for a list of categories. You simply pass it the parent category ID for any given category and it will recursively get all the parents further up the tree.

function getParentCategoriesById($parent_category_id,array $parents = []){

if(empty($parent_category_id)) {
    return [];
}

$parents[] = $parent_category_id;

$parent_category = DB::builder()->table('product_categories')->find($parent_category_id);

if(!empty($parent_category->parent)) {
    getParentCategoriesById($parent_category->parent,$parents);
}

return $parents;}

Let's say category id=100 has 2 parents (33->37), if I dump the $parents array just before the return, the results are:

Array
(
    [0] => 33
    [1] => 37
)
Array
(
    [0] => 33
)

The first array returned is the correct result, but I don't understand how the function is re-running and then instead returning only the first parent.

图片转代码服务由CSDN问答提供 功能建议

我希望有人可以提供帮助,这让我发疯了!

I 有一个简单的递归PHP函数,用于让所有父级访问任何给定的父级以获取类别列表。 您只需将任何给定类别的父类别ID传递给它,它将递归地获取树中所有父项。

  function getParentCategoriesById($ parent_category_id,array $ parents = [  ]){
 
if(空($ parent_category_id)){
 return []; 
} 
 
 $ parents [] = $ parent_category_id; 
 
 $ parent_category = DB :: builder() -  > table('product_categories') - > find($ parent_category_id); 
 
if(!empty($ parent_category-> parent)){
 getParentCategoriesById($ parent_category-> parent,$ parents); \  n} 
 
return $ parents;} 
   
 
 

如果我转储$ parents,我们说类别id = 100有2个父母(33-> 37) 在返回之前的数组,结果是:

数组
(
 [0] => 33 
 [1] => 37  
)
  
数组
(
 [0] => 33 
)
  
 
 

返回的第一个数组是正确的结果, 但我不明白该功能如何重新运行,然后只返回第一个父。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题