Search code examples
phparraysmultidimensional-arrayarray-mergearray-unique

How to merge an array with duplicate keys with array merge?


$cat1=array( "_id"=>new MongoId("562918fc2bad8c345d000029"),"name"=>"Category Two");


$cat2=array("_id"=>new MongoId("562918e62bad8c445d000029"),
"name"=>"Category One");

$categories=array();

$categories=array_merge($cat1,$cat2);

print_r($categories);

but it returns as follow

 array("_id"=>new MongoId("562918e62bad8c445d000029"),
"name"=>"Category One")

I tried array_unique too

array_unique(array_merge($cat1,$cat2))

But result was same as above
I know its not merging both array because both have same array keys. Instead its merging second into a first array, But how can I merge both arrays so it will look like following.

array(array( "_id"=>new MongoId("562918fc2bad8c345d000029"),"name"=>"Category Two"),array("_id"=>new MongoId("562918e62bad8c445d000029"),
    "name"=>"Category One"));

Have a look at live code http://viper-7.com/Oaa4zL


Solution

  • If you don't know how many categories will be there, then you can simply push them to the array.

    $allCat = array();
    $allCat[] = $cat1;
    $allCat[] = $cat2;
    .
    .
    .
    $allCat[] = $catN;
    
    print_r($allCat);