1

I have array:

$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
  ]];

And if $array[key][0] and $array[key][1] has same values, then I need to sum $array[key][2] and $array[key][3] only on duplicated $array[key][0] and $array[key][1] and combine into one key.

That's what I'm trying to achieve:

$array = [
  0 => [
    0 => 1500
    1 => 994
    2 => 9472
    3 => 592
  ]
  1 => [
    0 => 25
    1 => 5
    2 => 63
    3 => 47
  ]];

First and second values (1500 and 994) have to be unchanged.

Thanks for answers!

1 Answer 1

1
$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>';

Output:

Array
(
    [0] => Array
        (
            [0] => 1500
            [1] => 994
            [2] => 9472
            [3] => 592
        )

    [1] => Array
        (
            [0] => 25
            [1] => 5
            [2] => 63
            [3] => 47
        )

)

http://sandbox.onlinephpfunctions.com/code/940f06c43338d9785b7c47548a0dcbf6e4b2cd75

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.