Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 associative arrays into 1

I'm having trouble merging my arrays and not sure what I'm doing wrong. Consider the following code:

$array1 = [
    [ 'job' => '123', 'who' => 'Alpha' ],
    [ 'job' => '789', 'who' => 'Bravo' ]
];

$array2 = [
    [ 'job' => '123', 'when' => 'Today' ]
];

$desiredArray = [
    [ 'job' => '123', 'who' => 'Alpha', 'when' => 'Today' ],
    [ 'job' => '789', 'who' => 'Bravo', 'when' => '' ]
];

This is what I've been trying to do:

$newArray = [];

foreach ($array2 as $row) {
    foreach ($array1 as $record) {
        if ($row['job'] === $record['job']) {
            $tempArray = [
                'when' => $row['when']
            ];
            $newRecord = array_merge($record, $tempArray);
            array_push($newArray, $newRecord);
        };
    };
};

This kinda works, but the problem is when there isn't a match, it still needs to put the original record into my new array. I've tried putting some stuff outside the if statement, but my loops are getting stuck. Any help is appreciated.

like image 828
Waxi Avatar asked Jan 17 '26 22:01

Waxi


1 Answers

If you extract arrays with job as the key it is much easier. Just loop the first array and check for the same key in the second and merge:

$a1 = array_column($array1, null, 'job');
$a2 = array_column($array2, null, 'job');

foreach($a1 as $key => $val) {
    $result[] = isset($a2[$key]) ? $val + $a2[$key] : $val;
}

Or the same with a built-in:

$result = array_replace_recursive(array_column($array1, null, 'job'),
                                  array_column($array2, null, 'job'));

If you need to re-index from that:

$result = array_values($result);
like image 65
AbraCadaver Avatar answered Jan 19 '26 10:01

AbraCadaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!