输入数组:
[
[1 => 2],
[1 => 2],
[2 => 1],
[3 => 1],
]
我想要这个输出:
[
[1 => 4],
[2 => 1],
[3 => 1],
]
看起来像是一个很好的案例::
array_reduce()
对于最终结果,我正在使用$res = array_chunk(array_reduce($arr, function(&$current, $item) {
foreach ($item as $key => $value) {
if (!isset($current[$key])) {
$current[$key] = 0;
}
$current[$key] += $value;
}
return $current;
}, []), 1, true);
array_chunk()
通过识别唯一的组并仅将引用推向结果数组,您可以避免在循环后重新索引结果。 demo
$result = array();
foreach ($input as $subarray) {
foreach ($subarray as $key => $value) {
if (isset($result[$key])) {
$result[$key][$key] += $value;
} else {
$result[$key] = array($key => $value);
}
}
}
$result = array_values($result); // Convert from associative array to indexed array
$result = [];
foreach ($array as $row) {
$k = key($row);
if (!isset($ref[$k])) {
$ref[$k] = 0;
$result[][$k] =& $ref[$k];
}
$ref[$k] += $row[$k];
}
var_export($result);