I two arrays set out like this.
First array
Array
(
[0] => Array
(
[manufacture] => Moto
[name] => ZSX 125
[code] => ZS125-48A
[cc] => 125
[bike_type] => 3 Motorcycle
[title] => Mto ZSX 125
[about] => The ZSX
)
[1] => Array
(
[manufacture] => Moto
[name] => LSM 125
[code] => STR125YB
[cc] => 125
[bike_type] => 6 Endurancemotor
[title] => Moto
[about] => Moto
)
)
Second array
Array
(
[0] => Array
(
[id] => 183
[model] => ZS125-48A
[engine_brand] => 158FMI-B
[engine_type] => Single Cylinder
)
[1] => Array
(
[id] => 172
[model] => STR125YB
[engine_brand] => K154FMI
[engine_type] => Single Cylinder
)
)
As you can see 'code' from the first array is the same as 'model' from the second and there will always be a match.
This is the array i would like to have.
Array
(
[0] => Array
(
[id] => 183
[model] => ZS125-48A
[engine_brand] => 158FMI-B
[engine_type] => Single Cylinder
[manufacture] => Moto
[name] => ZSX 125
[code] => ZS125-48A
[cc] => 125
[bike_type] => 3 Motorcycle
[title] => Moto ZSX 125
[about] => The ZSX
)
[1] => Array
(
[id] => 172
[model] => STR125YB
[engine_brand] => K154FMI
[engine_type] => Single Cylinder
[manufacture] => Moto
[name] => LSM 125
[code] => STR125YB
[cc] => 125
[bike_type] => 6 Endurancemotor
[title] => Moto
[about] => Moto
)
)
Is this possible? i have tried array_merge and array_merge_recursive, but it only appends the second array onto the end of the first, it doesnt merge it on the keys.
Deceze's solution is perfect if the two arrays are synchronized (i.e. items with matching
code
and model
are at the same index in both arrays). If that is not the case you will need more than one line of code.
The arrays need to have string keys in order to be merged with
array_merge
. In this case you want to rekey the first one based on code
and the second based on model
. After rekeying you can merge them with array_merge_recursive
.
Rekeying is easy in PHP 5.5+:
// array_column will conveniently rekey when the second argument is null
$array1 = array_column($array1, null, 'code');
$array2 = array_column($array2, null, 'model');
A bit more complicated in earlier versions:
// array_map is a more complicated way to extract a column from an array
// and array_combine will do the rekeying
$array1 = array_combine(
array_map(function($i) { return $i['code']; }, $array1),
$array1);
$array2 = array_combine(
array_map(function($i) { return $i['model']; }, $array2),
$array2);
In both cases the final step would be the same:
$result = array_merge_recursive($array1, $array2);
0 comments:
Post a Comment