Cosmin
Cosmin

Reputation: 77

How to sum 2 multidimensional arrays that can have different sizes?

I have two multi dim arrasy, that I need to get the sum of them.

Arrays:

array:5 [▼
  0 => {#275 ▼
    +"pharmacy_name": "CVS"
    +"num": "6"
    +"reversed": "2"
  }
  1 => {#279 ▼
    +"pharmacy_name": "KROGER"
    +"num": "8"
    +"reversed": "4"
  }
  2 => {#283 ▼
    +"pharmacy_name": "PUBLIX"
    +"num": "11"
    +"reversed": "3"
  }
  3 => {#284 ▼
    +"pharmacy_name": "RITE AID"
    +"num": "0"
    +"reversed": "2"
  }
  4 => {#286 ▼
    +"pharmacy_name": "WALMART"
    +"num": "13"
    +"reversed": "5"
  }
]
array:4 [▼
  0 => {#288 ▼
    +"pharmacy_name": "CVS"
    +"num": "422"
    +"reversed": "243"
  }
  1 => {#289 ▼
    +"pharmacy_name": "RITE AID"
    +"num": "0"
    +"reversed": "1"
  }
  2 => {#290 ▼
    +"pharmacy_name": "WALGREENS"
    +"num": "209"
    +"reversed": "99"
  }
  3 => {#291 ▼
    +"pharmacy_name": "WALMART"
    +"num": "6"
    +"reversed": "3"
  }
]

I wrote some code(as you will see next), but the problem I have is that the arrays are now allwasy equal, as in some pharmacy_name can be in first array, but not in second, and vice versa(KROGER is in fist array, but not in second, so the result does not have KROGER). The code so far:

$total = [];
        foreach ($query as $key => $value) {
            foreach ($queryOV as $k => $val) {
                if(!isset($total[$value->pharmacy_name])){
                    $total[$value->pharmacy_name]['num'] =$value->num;
                    $total[$value->pharmacy_name]['reversed'] =$value->reversed;
                }
                if($value->pharmacy_name==$val->pharmacy_name){
                    $total[$value->pharmacy_name]['num'] += $val->num;
                    $total[$value->pharmacy_name]['reversed'] += $val->reversed;
                }
            }
        }

Summs the rest, but missed the KROGER.Please help, thanks!

Upvotes: 1

Views: 43

Answers (1)

Wojciech Jasiński
Wojciech Jasiński

Reputation: 1490

$total = [];
foreach (array_merge($a1, a2) as $x) {
    if (!array_key_exists($x->pharmacy_name, $total))
        $total[$x->pharmacy_name] = ['pharmacy_name' => $x->pharmacy_name, 'num'=> 0, 'reversed' => 0];
    $total[$x->pharmacy_name]['num'] += $x->num;
    $total[$x->pharmacy_name]['reversed'] += $x->reversed
}

Upvotes: 1

Related Questions