Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从两个键数组中查找重复项并对不同的键求和_Php_Arrays - Fatal编程技术网

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
        )

)