phpnerd
phpnerd

Reputation: 926

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

Upvotes: 1

Views: 225

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79024

No need to merge them:

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

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

Upvotes: 1

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

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);

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163642

You could do it manually and add them both to an array:

print_r(array(
    $cat1,
    $cat2
));

Upvotes: 1

Related Questions