Reputation: 1651
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.
Upvotes: 2
Views: 74
Reputation: 78994
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);
Upvotes: 4
Reputation: 28529
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);
Upvotes: 0
Reputation: 1774
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);
}
};
Upvotes: 3
Reputation: 40683
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
}
}
Upvotes: 2