0

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.

3
  • 1
    whats the problem in traditional looping ? Commented Dec 16, 2016 at 18:13
  • 1
    Nothing built in without nesting/chaining a few built in functions like array_column with array_combine and similar. Commented Dec 16, 2016 at 18:16
  • @HillaryClintonEmailRemover I dunno, i thought it was more efficient performance wise to do it using built in functions, thanks tho Commented Dec 16, 2016 at 18:29

2 Answers 2

1

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

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

3 Comments

he said non traditional
There's nothing not traditional as built in function for this
exectly what i thought i dunno why he wants to use some complex things to do simple tasks
1
$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!

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.