Php 从两个键数组中查找重复项并对不同的键求和
我有一个数组:Php 从两个键数组中查找重复项并对不同的键求和,php,arrays,Php,Arrays,我有一个数组: $array = [ 0 => [ 0 => 1500 1 => 994 2 => 155 3 => 530 ] 1 => [ 0 => 1500 1 => 994 2 => 9314 3 => 11 ] 2 => [ 0 => 25 1 => 5 2 => 63 3 => 4
$array = [
0 => [
0 => 1500
1 => 994
2 => 155
3 => 530
]
1 => [
0 => 1500
1 => 994
2 => 9314
3 => 11
]
2 => [
0 => 25
1 => 5
2 => 63
3 => 47
]
3 => [
0 => 1500
1 => 994
2 => 3
3 => 51
]];
如果$array[key][0]
和$array[key][1]
具有相同的值,那么我需要对重复的$array[key][2]
和$array[key][3]
进行求和,然后合并成一个键
这就是我想要实现的目标:
$array = [
0 => [
0 => 1500
1 => 994
2 => 9472
3 => 592
]
1 => [
0 => 25
1 => 5
2 => 63
3 => 47
]];
第一个和第二个值(1500和994)必须保持不变
谢谢你的回答
$array = [
0 => [
0 => 1500,
1 => 994,
2 => 155,
3 => 530,
],
1 => [
0 => 1500,
1 => 994,
2 => 9314,
3 => 11,
],
2 => [
0 => 25,
1 => 5,
2 => 63,
3 => 47,
],
3 => [
0 => 1500,
1 => 994,
2 => 3,
3 => 51,
],];
// create composite array key
$newArray = [];
foreach($array as $item) {
$compositeKey = $item[0] . '-' . $item[1];
$newArray[$compositeKey] = [
$item[0],
$item[1],
isset($newArray[$compositeKey][2]) ? $newArray[$compositeKey][2] + $item[2] : $item[2],
isset($newArray[$compositeKey][3]) ? $newArray[$compositeKey][3] + $item[3] : $item[3],
];
}
echo '<pre>';
print_r(array_values($newArray));
echo '</pre>';
Array
(
[0] => Array
(
[0] => 1500
[1] => 994
[2] => 9472
[3] => 592
)
[1] => Array
(
[0] => 25
[1] => 5
[2] => 63
[3] => 47
)
)