Search code examples
phparrayssortingmultidimensional-arrayarray-merge

Sum values of a Multidimensional Array with repeating var


So I'm trying to merge duplicated values of an array, but also sum the values.

So atm I got this array:

[969] => Array
    (
        [zip] => 8043
        [total] => 2355.00
        [orders] => 1
    )

[968] => Array
    (
        [zip] => 8225
        [total] => 1195.00
        [orders] => 1
    )

[967] => Array
    (
        [zip] => 8043
        [total] => 1640.00
        [orders] => 1
    )

I would like them to merge based upon "zip" and become something like this:

     [969] => Array
    (
        [zip] => 8043
        [total] => 3995.00
        [orders] => 2
    )

[968] => Array
    (
        [zip] => 8225
        [total] => 1195.00
        [orders] => 1
    )

Solution

  • EDITED ANSWER, WILL WORK WITH ARRAYS OF RANDOM KEYS

    Originally, I had this working for arrays with keys 0...infinity but they had to have all keys and be in order. This works with any number of array keys and in any order.

    <?php
    
    $array[10] = Array(
        'zip' => 8043,
        'total' => 2355.00,
        'orders' => 1
      );
    
    $array[1] = Array(
          'zip' => 8225,
          'total' => 1195.00,
          'orders' => 1
      );
    
    $array[44] = Array(
          'zip' => 8225,
          'total' => 1195.00,
          'orders' => 1
      );
    
    $array[2] = Array(
          'zip' => 8043,
          'total' => 1640.00,
          'orders' => 1
      );
    $array[3] = Array(
          'zip' => 8043,
          'total' => 3434.00,
          'orders' => 1
      );
    
    function mergeSimilarZip($array) {
      sort($array);
      $newArray = array();
      $k = 0;
      for ($i = 0; $i < count($array); $i++) {
          $newArray[$k]['zip'] = $array[$i]['zip'];
          $newArray[$k]['total'] = $array[$i]['total'];
          $newArray[$k]['orders'] = $array[$i]['orders'];
          for ($j = $i + 1; $j < count($array); $j++) {
            if ($array[$i]['zip'] == $array[$j]['zip']) {
              $newArray[$k]['total'] += $array[$j]['total'];
              $newArray[$k]['orders']++;
              unset($array[$j]);
            }
          }
        sort($array);
        $k++;
      }
      return $newArray;
    }
    
    $newArray = mergeSimilarZip($array);
    
    var_dump($newArray);
    

    That outputs:

    array (size=2)
      0 => 
        array (size=3)
          'zip' => int 8043
          'total' => float 7429
          'orders' => int 3
      1 => 
        array (size=3)
          'zip' => int 8225
          'total' => float 2390
          'orders' => int 2