开发者

php getting array levels in the recursion

开发者 https://www.devze.com 2023-01-27 14:28 出处:网络
I have the next tree-array: $arr = array( \'id\' => 1431, \'children\' => arra开发者_StackOverflow中文版y(

I have the next tree-array:

$arr = 
array(
 'id' => 1431,
 'children' => arra开发者_StackOverflow中文版y(
  1432 => array(
   'id' => 1432,
   'children' => array(
    1433 => array(
     'id' => 1433,
     'children' => array(),
    ),
    1434 => array(
     'id' => 1434,
     'children' => array(),
    ),
   ) 
  ),
  1435 => array(),
   'id' => 1435,
   'children' => array(
    1436 => array(
     'id' => 1436,
     'children' => array(
      1437 => array(
       'id' => 1437,
       'children' => array(),
      ),
      1438 => array(
       'id' => 1438,
       'children' => array(),
      ),
      1439 => array(
       'id' => 1439,
       'children' => array(),
      ),
     ),
    ),
   ),
 ),
);

My task to get generations array from this array. My output should be the next:

Array(
[1] = Array(
  [1432] = ...
  [1435] = ...
),
[2] = Array(
  [1433] = ...
  [1434] = ...
  [1436] = ...
),
[3] = Array(
  [1437] = ...
  [1438] = ...
  [1439] = ...
),
)

But now my output the next (without 1346 element):

Array(
[1] = Array(
  [1432] = ...
  [1435] = ...
),
[2] = Array(
  [1433] = ...
  [1434] = ...
),
[3] = Array(
  [1437] = ...
  [1438] = ...
  [1439] = ...
),
)

What is wrong in my function?

public function getGenerations($userTree, $currGeneration = 0, $result = array())
{
    print_r($userTree);
    $currGeneration++;
    if (!empty($userTree) && !empty($userTree['children'])) {
        foreach($userTree['children'] as $k => $v) {
            $currUser = $v;
            unset($currUser['children']);
            $result[$currGeneration][$k] = $currUser;
            $result += $this->getGenerations($v, $currGeneration, $result);
        }
    }
    return $result;
}

I call this function like this: $res = getGenerations($arr); Thank you in advance. Sorry for my english.


You could pass the result array as a reference instead of returning and then joining it with the local result array:

public function getGenerations($userTree, $currGeneration = 0, &$result = array())
{
    print_r($userTree);
    $currGeneration++;
    if (!empty($userTree) && !empty($userTree['children'])) {
        foreach($userTree['children'] as $k => $v) {
            $currUser = $v;
            unset($currUser['children']);
            $result[$currGeneration][$k] = $currUser;
            $this->getGenerations($v, $currGeneration, $result);
        }
    }
    return $result;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号