Array merge based on key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vale73
Forum Newbie
Posts: 1
Joined: Wed Dec 01, 2010 9:35 am

Array merge based on key

Post by vale73 »

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 ) )
curlybracket
Forum Commoner
Posts: 59
Joined: Mon Nov 29, 2010 2:40 pm

Re: Array merge based on key

Post by curlybracket »

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:

Code: Select all

$arr1 = array('id' => 3, 'color' => 'black');
$arr2 = array('id' => 3, 'size' => 'big');

$result = array_merge($arr1, $arr2);
print_r($result);
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.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Array merge based on key

Post by Jonah Bron »

Code: Select all

foreach ($a as &$car) {
    foreach ($b as $otherCar) {
        if ($otherCar->car_id == $car->car_id) {
            $car->year = $otherCar->year;
            break;
        }
    }
}
Notice the '&' on the first line. That indicates that the value should be passed by reference. Without that, it would not merge the arrays.
Post Reply