简体   繁体   中英

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.

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);

I think you reversed the loop, I also added an $exist variable to check if an item from $array1 doesn't exists in $array2 (So i can add it)

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

Start from one of the 2 arrays and merge with the other. Flag what's not found:

$newArray = $array1;

foreach ($array2 as $row) { //You need to eventually deal with all of these somehow
    $found = false;
    foreach ($newArray as $key => $record) {
        if ($row['job'] === $record['job']) {
            $found = true;
            $newArray[$key] += $row; //Merge if found
        }
    }
    if (!$found) {
       $newArray[] = $row; //Append if not found
    }
}

You add the when key in the array1, you can do it like this way.

$jobs_time = array_combine(array_column($array2, 'job'), array_column($array2, 'when'));
$result = array_map(function($v)use($jobs_time){
    $v['when'] = isset($jobs_time[$v['job']]) ? $jobs_time[$v['job']] : '';
    return $v;
}, $array1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM