I have the following PHP array:
Array
(
[13] => Array
(
[bond] => 5
[level] => 1
[sub] => Array
(
[1] => Array
(
[bond] => 7
[level] => 2
[sub] => Array
(
[7] => Array
(
[bond] => 9
[level] => 3
[sub] => Array
(
)
)
[18] => Array
(
[bond] => 6
[level] => 3
[sub] => Array
(
)
)
[24] => Array
(
[bond] => 9
[level] => 3
[sub] => Array
(
)
)
)
)
)
)
[14] => Array
(
[bond] => 4
[level] => 1
[sub] => Array
(
)
)
[21] => Array
(
[bond] => 5
[level] => 1
[sub] => Array
(
[19] => Array
(
[bond] => 8
[level] => 2
[sub] => Array
(
)
)
)
)
)
How can I count, for each entry, the count of its sub entries, if any?
So to these keys/values should be added to the array:
[13]['count'] = 1;
[13][1]['count'] = 3;
[13][1][7]['count'] = 0;
...
[14]['count'] = 0;
... etc
I can't wrap my head around this. Is it a recursive function? Is it a while(true) loop inside a foreach loop? Do I use global variables to alter the array?
I tried everything I could come up with and I just can't do it.
EDIT:
Here's my solution for 2 levels deep. I am unable to make this recursively work for infinite levels:
foreach($items as $cell=>$data){
$count = count($data['sub']);
$items[$cell]['count'] = $count;
if ($count){
foreach($data['sub'] as $cell2=>$data2){
$count = count($data2['sub']);
$items[$cell]['sub'][$cell2]['count'] = $count;
}
}
}