获取(父/子)数组的父节点的路径

时间:2022-05-25 13:38:44

Given the following array:

给出以下数组:

array(..) {
  [1111]=>
  &array(3) {   
    ["category_id"]=>
    int(1111)
    ["parent_id"]=>
    int(0)
    ["children"]=>
    array(2) {
      [2222]=>
      &array(3) { 
        ["category_id"]=> 
        int(2222)
        ["parent_id"]=>
        int(1111)  
        ["children"]=>
            array(2) {
            [5555]=>
              &array(1) { 
                ["category_id"]=> 
                int(5555)
                ["parent_id"]=>
                int(2222)
              }
      }
      [3333]=>
      &array(2) { 
        ["category_id"]=>
        int(3333)
        ["parent_id"]=>
        int(1111)
      }  
  }

Assuming that the array depth is unknown, How can I determine the path to the parent node?

假设数组深度未知,我如何确定父节点的路径?

For example, for category_id = 5555 I should get the following result: 0, 1111,2222. For category_id = 3333 it would be 0,1111

例如,对于category_id = 5555,我应该得到以下结果:0,1111,2222。对于category_id = 3333,它将是0,1111

1 个解决方案

#1


1  

One approach:

一种方法:

function findParent($node, $array, &$parents) {
    if (array_key_exists($node, $array)) {
        $parents[] = $array[$node]['parent_id'];
    }
    else {
        foreach ($array as $item) {
            if (array_key_exists('children', $item)) {
                $parents[] = $item['parent_id'];
                findParent($node, $item['children'], $parents);
            }
        }
    }
}

findParent(5555, $A, $parents);

#1


1  

One approach:

一种方法:

function findParent($node, $array, &$parents) {
    if (array_key_exists($node, $array)) {
        $parents[] = $array[$node]['parent_id'];
    }
    else {
        foreach ($array as $item) {
            if (array_key_exists('children', $item)) {
                $parents[] = $item['parent_id'];
                findParent($node, $item['children'], $parents);
            }
        }
    }
}

findParent(5555, $A, $parents);