PHP Multidimensional Array Merge based on keys

395 views Asked by At

i have this two arrays:

$array1 = [
  '1' => 285.52,
  '2' => 427.76
];

$array2 = [
  '1' => 123.44,
  '2' => 48.32
];

The keys on each of them are the id for the client, the first one is the amount owed and the second one is the amount payed, i want to achieve the following:

$mergedArrays = [
   '1' => [
     'owed'  => 285.52,
     'payed' => 123.44
   ],
   '2' => [
     'owed'  => 427.76,
     'payed' => 48.32
   ]
];

I was wondering if there's a PHP function to do so, i tried with array_merge_recursive but it just makes an array with the four elements together.

Any help would be really appreciated.

2

There are 2 answers

0
Wolverine On
$array1 = [
  '1' => 285.52,
  '2' => 427.76
];

$array2 = [
  '1' => 123.44,
  '2' => 48.32
];

$final_arr = array_map(function($a1, $a2) {
    return array(
        'owed' => $a1,
        'paid' => $a2
    );
}, $array1, $array2);

$final_arr = array_combine(array_keys($array1), $final_arr);

var_dump($final_arr);

Based on the comment, it seems you're looking for built-in PHP functions to do the task for you rather than going for traditional looping. But the looping method provided by Fabio is the simplest one you could go for without any other complicated approaches. I've tried my best to provide you the solution using the core PHP functions. Hope you're happy with it!

3
Fabio On

you can loop in the first array and merge the second according to keys

foreach($array1 as $key => $val) {
    $mergedArrays[$key] = array('owed' => $val, 'payed' => $array2[$key]);
}

sample