Recursive function to calculate totals from bottom up in array
I have an array that looks like this:
Array
(
[0] => Array
(
[id] => 5
[title] => Books
[total_links] => 3
[subcategories] => Array
(
[0] => Array
(
[id] => 6
[title] => Jeffrey Archer
[total_links] => 1
开发者_如何学C [subcategories] => Array
(
[0] => Array
(
[id] => 8
[title] => Political
[total_links] => 2
[subcategories] => Array
(
)
)
[1] => Array
(
[id] => 9
[title] => Thriller
[total_links] => 5
[subcategories] => Array
(
)
)
)
)
I need a recursive function that will loop through the subcategories
from bottom up, adding the total_links
together and changing the value of the total_links
in the array above it.
So in the end the array will have total_links
values of:
- Books = 11
- Jeffrey Archer = 8
- Political = 2
- Thriller = 5
And preferably without the use of the SPL functions (but if there is no other way then feel free).
Any ideas?
This is untested, but should do the trick
function do_sums(&$array) {
if (is_array($array['subcategories'])) {
foreach ($array['subcategories'] as $category_array) {
$array['total_links'] += do_sums($category_array); // recurse down first
}
}
return($array['total_links']);
}
$your_array = array(...)
do_sums($your_array);
Code: (Demo with extended sample data for testing)
function sum_links(&$array){ // make $array modifiable by reference
foreach($array as &$item){ // make $item modifiable by reference
if(!empty($item['subcategories'])){ // only recurse if there are children in subcategories
$item['total_links']+=array_sum(array_column(sum_links($item['subcategories']),'total_links'));
// recursion returns full subarray, extract desired column data, add sum to the original value
}
}
return $array; // return the full & updated array
}
var_export(sum_links($array));
/* or because $array is modified by reference...
sum_links($array);
var_export($array);
*/
精彩评论