我在PHP中有一个2D数组,我需要先聚合其中的数据,然后再用PHPExcel将其保存到EXCEL工作表中。我的数据已按国家/地区排序。每个子数组都有一个国家名称。我想做的是为每个国家/地区添加“ 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
)
我知道类似的PHP函数array_walk_recursive
可能会有所帮助,但我不知道该怎么做。
循环您的数组,并以“国家/地区”为键并添加实时来构建临时结果。然后只需将值与原始数组合并即可:
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句