1
$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

2
  • what result you want? Commented Oct 22, 2015 at 17:36
  • It should be merged like the last one.. I have mentioned it Commented Oct 22, 2015 at 17:41

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it is. It pushes category array to allCat array.
1

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

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

Comments

1

No need to merge them:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.