hi,
I've got two php arrays
The first array represents the total distance covered by a car, and I call it
$a
Array ( [0] => stdClass Object ( [total_distance] => 1000 [car_id] => 1 ) [1] => stdClass Object ( [total_distance] => 500 [car_id] => 2 ) )
The second array, is the array of cars, and I call it
$b
Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 ) )
Is it possible to merge these arrays, provided they have the car_id key in common?
The resulting array should be:
$c
Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 [total_distance] => 1000 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 [total_distance] => 500 ) )
Array merge based on key
Moderator: General Moderators
-
curlybracket
- Forum Commoner
- Posts: 59
- Joined: Mon Nov 29, 2010 2:40 pm
Re: Array merge based on key
I think that this is an algorythmic problem and you will need to write code using few foreach() and if() instructions, key_exists() and array_merge() functions. Basic functioning of array_merge is:
which is promising for you. But your problem is bit more complicated: you have two (or more?) arrays of objects. You don't know how many objects with same id can be stored in first and second array. You can have 3 objects with same id in first array and 2 objects with that id in second array - this can be complicated. I think you should write good alogrythm for this problem and code it. Maybe your problem is simpler: just one object with the same id in one array - You didn't write nothing about that.
Code: Select all
$arr1 = array('id' => 3, 'color' => 'black');
$arr2 = array('id' => 3, 'size' => 'big');
$result = array_merge($arr1, $arr2);
print_r($result);
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
Re: Array merge based on key
Code: Select all
foreach ($a as &$car) {
foreach ($b as $otherCar) {
if ($otherCar->car_id == $car->car_id) {
$car->year = $otherCar->year;
break;
}
}
}