lwc Posted January 19, 2007 Share Posted January 19, 2007 I want each "count" key to contain its own count (if available) + each of its childs' counts.[code]Array( [level0a] => Array ( [sub] => Array ( [level1a] => Array ( [sub] => Array ( [level2a] => Array ( [sub] => Array ( [level3a] => Array ( [count] => 1 ) ) ) [level2e] => Array ( [count] => 5 ) ) [count] => 2 ) ) ) [level0d] => Array ( [sub] => Array ( [level1d] => Array ( [sub] => Array ( [level2d] => Array ( [count] => 3 ) ) ) ) ) [level0c] => Array ( [sub] => Array ( [level1c] => Array ( [count] => 4 [sub] => Array ( [level2z] => Array ( [count] => 6 ) ) ) ) ))[/code]I've only managed to affect the root keys by using:[code]function multi_array_sum_key($a, $subkey = false, $sumkey = false) { if(!is_array($a)) return $a; foreach($a as $key=>$value) if ($subkey && $sumkey) { if (isset($value[$subkey]) && is_array($value[$subkey])) $total += multi_array_sum_key($value[$subkey], $subkey, $sumkey); if (isset($value[$sumkey]) && intval($value[$sumkey])) $total += $value[$sumkey]; } else $total += multi_array_sum_key($value); return $total;}function multi_array_sum($menu, $subkey = false, $sumkey = false) { foreach($menu as $key => $value) { if (isset($value[$subkey]) && is_array($value[$subkey])) { $total += multi_array_sum_key($value[$subkey], $subkey, $sumkey); $menu[$key][$sumkey] += $total; } $total=0; }return $menu;}$menu = multi_array_sum($menu, 'sub', 'count');[/code]Outputs (note the 8, 3 & 10):[code]Array( [level0a] => Array ( [sub] => Array ( [level1a] => Array ( [sub] => Array ( [level2a] => Array ( [sub] => Array ( [level3a] => Array ( [count] => 1 ) ) ) [level2e] => Array ( [count] => 5 ) ) [count] => 2 ) ) [count] => 8 ) [level0d] => Array ( [sub] => Array ( [level1d] => Array ( [sub] => Array ( [level2d] => Array ( [count] => 3 ) ) ) ) [count] => 3 ) [level0c] => Array ( [sub] => Array ( [level1c] => Array ( [count] => 4 [sub] => Array ( [level2z] => Array ( [count] => 6 ) ) ) ) [count] => 10 ))[/code]The reason only the root keys are affected is I don't manage to preserve $menu inside function multi_array_sum. Does anyone know how can I preserve it, so I can affect each child's count too?Thanks! Link to comment https://forums.phpfreaks.com/topic/34883-setting-deep-values-in-multidimentional-associative-arrays/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.