I have an array like this :
$foo_array = array (
[3533] => 4 ,
[353] => 3 ,
[351] => 2 ,
[35] => 0 ,
);
this is an example array, it has many elements and it is dynamic from the database, but I want to say an example for you!
each key of an array has a parent like this, for example, 353 is the parent of 3533 and ...
Now I want to sum count of each parent from childrens count. the true result of count for key 35 must be 9, but I can't receive this result! I create foreach for this array and get all parents, after that plus count of that child to each parent of that but unfortunately get a bad result!
CodePudding user response:
This will give you an array with the parent as the index and the values of parent and children:
foreach($foo_array as $key => $val) {
$result[$key] = array_intersect_key($foo_array, array_flip(preg_grep("/^$key/", array_keys($foo_array))));
}
Yields:
Array
(
[3533] => Array
(
[3533] => 4
)
[353] => Array
(
[3533] => 4
[353] => 3
)
[351] => Array
(
[351] => 2
)
[35] => Array
(
[3533] => 4
[353] => 3
[351] => 2
[35] => 0
)
)
So you can then access by parent:
echo array_sum($result[35]);
Or you could use $result[$key] = array_sum( . . . . . );
in the loop.
If you are only concerned with 35
for example then:
$key = 35;
$result = array_sum(array_intersect_key($foo_array, array_flip(preg_grep("/^$key/", array_keys($foo_array)))));