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

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.

  • 写回答

1条回答 默认 最新

  • doonbfez815298 2017-09-06 10:42
    关注

    You should pass reference to $parents in internal call to getParentCategoriesById()

    function getParentCategoriesById($parent_category_id, array &$parents = []) { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?