php - Recursive function to calculate totals from bottom up in array -



php - Recursive function to calculate totals from bottom up in array -

i have array looks this:

array ( [0] => array ( [id] => 5 [title] => books [total_links] => 3 [subcategories] => array ( [0] => array ( [id] => 6 [title] => jeffrey archer [total_links] => 1 [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 recursive function loop through subcategories bottom up, adding total_links , changing value of total_links in array above it.

so in end array have total_links values of:

books = 11 jeffrey archer = 8 political = 2 thriller = 5

and preferably without utilize of spl functions (but if there no other way sense free).

any ideas?

this untested, should trick

function do_sums(&$array) { if (is_array($array['subcategories'])) { foreach ($array['subcategories'] $category_array) { $array['total_links'] += do_sums($category_array); // recurse downwards first } } return($array['total_links']); } $your_array = array(...) do_sums($your_array);

php arrays recursion

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -