php 获取无限极 父级下面所有的子级(包含子级的子级)

$categories = array(
            array('typeid' => 1, 'parentid' => 0, 'name' => 'Category 1'),
            array('typeid' => 2, 'parentid' => 0, 'name' => 'Category 2'),
            array('typeid' => 3, 'parentid' => 1, 'name' => 'Subcategory 1.1'),
            array('typeid' => 4, 'parentid' => 1, 'name' => 'Subcategory 1.2'),
            array('typeid' => 5, 'parentid' => 3, 'name' => 'Sub-subcategory 1.1.1'),
            array('typeid' => 6, 'parentid' => 2, 'name' => 'Subcategory 2.1')
);
function getResult($categories){
    $result = [];
    // 遍历分类数组
    foreach ($categories as $category) {
        $parentId = $category['parentid'];
        $categoryId = $category['typeid'];

        if (!isset($result[$parentId])) {
             $result[$parentId] = array();
        }


        $result[$parentId][] = $categoryId;
     }

     foreach ($result as $parentId => &$children) {
        $descendants = array();
        foreach ($children as $childId) {
           $descendants = array_merge($descendants, self::getChildren($childId, 
                   $result));
        }
        $children = array_unique(array_merge($children, $descendants));
     }

     return $result;
}

//定义一个方法
function getChildren($categoryId, $categories) {
   $children = array();

   if (isset($categories[$categoryId])) {
          foreach ($categories[$categoryId] as $childId) {
              $children[] = $childId;
              $children = array_merge($children, self::getChildren($childId,                                 
                   $categories));
          }
   }

   return $children;
}





var_dump(getResult($categories));
//打印结果
array(4) {
  [0]=>
  array(6) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
    [3]=>
    int(5)
    [4]=>
    int(4)
    [5]=>
    int(6)
  }
  [1]=>
  array(3) {
    [0]=>
    int(3)
    [1]=>
    int(4)
    [2]=>
    int(5)
  }
  [3]=>
  array(1) {
    [0]=>
    int(5)
  }
  [2]=>
  &array(1) {
    [0]=>
    int(6)
  }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值