我有一个多维数组,我需要总结具有相同键的值。
的print_r($输入)
Array
(
[0] => Array
(
[id] => colors
[power] => Array
(
[green] => 12
[red] => 5
[orange] => 9
[black] => 6
[white] => 5
[blue] => 11
)
)
[1] => Array
(
[id] => colors
[power] => Array
(
[green] => 20
[red] => 40
[orange] => 80
[black] => 60
[white] => 100
[blue] => 110
)
)
[2] => Array
(
[id] => glossycolor
[power] => Array
(
[green] => 20
[red] => 40
[orange] => 80
[black] => 60
[white] => 100
[blue] => 110
)
)
)
我需要结果像
Array
(
[0] => Array
(
[id] => colors
[power] => Array
(
[green] => 32
[red] => 45
[orange] => 89
[black] => 66
[white] => 105
[blue] => 121
)
)
[1] => Array
(
[id] => glossycolor
[power] => Array
(
[green] => 20
[red] => 40
[orange] => 80
[black] => 60
[white] => 100
[blue] => 110
)
)
)
我试图使用array_shift对值进行排序并对子数组值求和但是我失败了
$finalRate = array_shift($inputs);
foreach ($inputs as $val) {
foreach ($val as $key => $val) {
$finalRate[$key] += $val;
}
}
但失败并返回空数组。
答案 0 :(得分:1)
$array1 = array_slice($input,0,1); //slicing first value of $input i.e Array([0]=>array)
$array2 = array_slice($input,1,1); //slicing second value of $input i.e Array([1]=>array)
$array = array_sum_values($array1,$array2); //summing values of two arrays
$input = array_splice($input,0,2,$array) //Removing [0] and [1] from $input and replacing with $array.
请参阅PHP手册了解更多详情。
答案 1 :(得分:1)
假设你的数组总是具有相同的结构:
$outcome = array();
foreach ($colors as $array) {
$id = $array['id'];
if (array_key_exists($id, $outcome)) {
foreach ($array['power'] as $color => $value) {
$outcome[$id]['power'][$color] += $value;
}
continue;
}
$outcome[$array['id']] = $array;
}
array_values($outcome);
答案 2 :(得分:0)
这可能不是解决此问题的最有效方式..但它有效且易于实施:
$arr = array(
0 => array(
'id' => 'colors',
'power' => array(
'green' => 12,
'red' => 5,
'orange' => 9,
'black' => 6,
'white' => 5,
'blue' => 11,
),
),
1 => array(
'id' => 'colors',
'power' => array(
'green' => 20,
'red' => 40,
'orange' => 80,
'black' => 60,
'white' => 100,
'blue' => 110,
),
),
2 => array(
'id' => 'glossycolors',
'power' => array(
'green' => 20,
'red' => 40,
'orange' => 80,
'black' => 60,
'white' => 100,
'blue' => 110,
),
),
);
foreach ( $arr as $k1 => $v1 ) {
foreach ( $arr as $k2 => $v2 ) {
if ( $k1 === $k2 ) continue;
if ( ! isset( $arr[ $k1 ] ) || ! isset( $arr[ $k2 ] ) ) continue;
if ( $v1['id'] === $v2['id'] ) {
foreach ( $v2['power'] as $power_k => $power_v ) {
$arr[$k1]['power'][$power_k] += $power_v;
}
unset( $arr[$k2] );
}
}
}
print_r( $arr );
这导致:
Array
(
[0] => Array
(
[id] => colors
[power] => Array
(
[green] => 32
[red] => 45
[orange] => 89
[black] => 66
[white] => 105
[blue] => 121
)
)
[2] => Array
(
[id] => glossycolors
[power] => Array
(
[green] => 20
[red] => 40
[orange] => 80
[black] => 60
[white] => 100
[blue] => 110
)
)
)
所以基本上,它循环遍历同一个数组两次,并对常见'id'元素的值进行求和,然后从数组中删除第二个副本,只留下原始数据与后者的总和。干杯