Php 嵌套数组中的子级递归计数+;通过引用更改值
我知道这是基本的递归,但我还是被卡住了:( 我需要计算每个元素下面有多少个元素(子元素、孙子元素等等),并将该值写入原始数组 我的示例阵列:Php 嵌套数组中的子级递归计数+;通过引用更改值,php,arrays,recursion,reference,Php,Arrays,Recursion,Reference,我知道这是基本的递归,但我还是被卡住了:( 我需要计算每个元素下面有多少个元素(子元素、孙子元素等等),并将该值写入原始数组 我的示例阵列: $table = [ 1 => [ 'id' => 1, 'children_count' => 0 ], 2 => [ 'id' => 2, 'children_count' => 0, 'children' => [ 3 => [
$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链接:children\u count是否也有子女或孙子的计数?是的,对不起,我的不好。将此添加到OP..Post您的预期输出@SubjectXelement 7有3个子女?这是一个问题吗?不,是的,但您的示例计数了3个子女:(我想你已经得到了你想要的@SubjectX good one splash58+1是的,它很有效。从我上学的时候起,我就认为它可以短一些,但它不起作用.)。。
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);