PHP如何聚合2维数组

我有一个二维数组在PHP中,我需要聚集它的数据,然后将其保存到EXCEL表与PHPExcel。 我的数据已经按国家sorting。 每个子arrays都有一个国家名称。 我想要做的是在每个国家添加一个“LIVE”字段的总数。 我的表看起来像这样:

[ [314] => Array ( [Country] => France [provider] => HIberica [status] => inactive [# per status] => 1 [Live] => 0 ) [315] => Array ( [Country] => France [provider] => HIberica [status] => active [# per status] => 4223 [Live] => 4171 ) [316] => Array ( [Country] => United States [provider] => HarperC [status] => pending [# per status] => 69 [Live] => 0 ) [317] => Array ( [Country] => United States [provider] => HC [status] => inactive [# per status] => 2582 [Live] => 0 ) [318] => Array ( [Country] => United States [provider] => HC [status] => active [# per status] => 16217 [Live] => 16217 ) [319] => Array ( [Country] => United States [provider] => H UK [status] => active [# per status] => 70 [Live] => 70 ) ] 

我想要的最终结果是为每个国家添加一个子数组来保存LIVE字段的总数,就像这样:

  [320] => Array ( [Country] => United States [provider] => All Providers [status] => active [# per status] => NULL [Total Live] => 7000 # the total per country goes here ) 

我知道像array_walk_recursive PHP函数可以帮助,但我不知道该怎么做。

循环你的数组,并build立一个临时的结果与国家为关键,并添加Live。 然后,将这些值与原始数组合并:

 foreach($array as $sub) { if(!isset($result[$sub['Country']])) { $result[$sub['Country']] = array('Country' => $sub['Country'], 'Total Live' => $sub['Live'], 'provider' => 'All Providers', 'status' => 'active', '# per status' => 'NULL'); } else { $result[$sub['Country']]['Total Live'] += $sub['Live']; } } $array = array_merge($array, array_values($result)); 

首先find每个国家的所有生命,而不是像你想要的那样创build临时数组,然后把它推到你的数组中。

 $subArrOfLive = []; foreach($YOUR_ARR as $val){ $currCountry = $val["Country"]; $currLive = $val["Live"]; if(!isset($subArrOfLive[$currCountry])) { $subArrOfLive[$currCountry] = $currLive; }else{ $subArrOfLive[$currCountry] += $currLive; } } foreach($subArrOfLive as $key => $val){ $temp = array( "Country" => $key, "provider" => "All Providers", "status" => "active", "# per status" => NULL, "Total Live" => $val ); $YOUR_ARR[] = $temp ; }