嵌套数组中子数组的递归计数+根据引用更改值


Recursive count of children in nested arrays + changing values by reference

我知道这是基本的递归,但我还是卡住了:(

我需要计算每个元素下面有多少个元素(子元素,孙子元素,…),并将该值写入原始数组。

我的示例数组:

$table = [
1 => [
    'id' => 1,
    'children_count' => 0
],
2 => [
    'id' => 2,
    'children_count' => 0,
    'children' => [
        3 => [
            'id' => 3,
            'children_count' => 0,
            'children' => [
                4 => [
                    'id' => 4,
                    'children_count' => 0,
                    'children' => [
                        5 => [
                            'id' => 5,
                            'children_count' => 0
                        ],
                        6 => [
                            'id' => 6,
                            'children_count' => 0
                        ]
                    ]
                ]
            ]
        ]
    ]
]    
];
我的递归代码:
function count_children(&$array){
    foreach($array['children'] as &$child){
        if(isset($child['children'])){
            $array['children_count'] += count_children($child);
        }
        else return 1;
    }
}

调用递归:

//call for each root element
foreach($table as &$element){
    if(isset($element['children'])) count_children($element);
}
预期输出:

$table = [
1 => [
'id' => 1,
'children_count' => 0
 ],
 2 => [
'id' => 2,
'children_count' => 4,
'children' => [
    3 => [
        'id' => 3,
        'children_count' => 3,
        'children' => [
            4 => [
                'id' => 4,
                'children_count' => 2,
                'children' => [
                    5 => [
                        'id' => 5,
                        'children_count' => 0
                    ],
                    6 => [
                        'id' => 6,
                        'children_count' => 0
                    ]
                ]
            ]
        ]
    ]
]
]    
];

我哪里说错了?我的函数做了一些事情,元素3的值为1,但仅此而已。

这里是ideone链接:http://ideone.com/LOnl3G

function count_children(&$table){
  $count1 = 0;
  foreach($table as &$array) {
    $count = 0;
    if (isset($array['children'])) {
      $count += count($array['children']);
      $count += count_children($array['children']);
    }
    $array['children_count'] = $count;
    $count1 += $count;
  }
  return $count1; 
}
count_children($table);
print_r($table);