我有一个两维数组如下。
array(
(int) 0 => array(
'Chrome' => '10',
'Firefox' => '3',
'Internet Explorer' => '1',
'Safari' => '1',
'Mobile' => (int) 0,
'Others' => (int) 0
),
(int) 1 => array(
'Chrome' => '5',
'Firefox' => '2',
'Safari' => '2',
'Internet Explorer' => '1',
'Opera' => '1',
'Mobile' => (int) 0,
'Others' => (int) 0
)
)
我想为相同的键添加值,并按如下方式将其放入单个数组中。
array(
'Chrome' => '15',
'Firefox' => '5',
'Internet Explorer' => '2',
'Safari' => '3',
'Opera' => '1',
'Mobile' => '0'
'Others' => '0'
)
请给我解决方案。
答案 0 :(得分:3)
迭代子数组并接管键和值对。如果它们存在,请将值(整数算术求和运算)添加到现有值。
完成迭代子数组后,结果就准备好了。
$array = array();
foreach ($subArrays as $subArray)
{
foreach ($subArray as $key => $value)
{
isset($array[$key]) || $array[$key] = 0;
$array[$key] += (int) $value;
}
}
// ready, but make all strings:
$array = array_map('strval', $array);