Dean219 Dean219 - 3 months ago 7
PHP Question

Correct way to add two elements to array and keep default index

I'm having an issue with an array, I wish to put 2 elements into my array together in the same element within the array but keep the default index. Currently I have this in my array :

Array (
[0] => 2
[1] => MongoId Object ( [$id] => 57b99696ce2350100b000029 )
[2] => 1
[3] => MongoId Object ( [$id] => 57b998ccce2350181700002b )
[4] => 1
[5] => MongoId Object ( [$id] => 57b99a84ce2350100b00002b ) )


and I wish to have something like this, I think:

Array (
[0] => [number]=>2, MongoId Object ( [$id] => 57b99696ce2350100b000029 )
[1] => [number]=>1, MongoId Object ( [$id] => 57b998ccce2350181700002b )
[2] => [number]=>1,MongoId Object ( [$id] => 57b99a84ce2350100b00002b )
)


I wish to retain the default key as well as have two other values, I have tried a few methods but none resulted in the elements being paired together as I want:

Currently (above) I tried :

$array = array_merge( $array,array( $number,$doc[_id] ) );


I also tried :

$array = array_merge( $array,array( $number=>$doc[_id] ) );


and:

array_push($array, $doc[_id], $number);
//asked here on SO earlier but this adds onto the end of an array both elements rather than adding both together into a single element


Can anyone advise the correct way to add two elements as a pair together whilst maintaining the default key/index value of the array.

Answer

You can just append an array at the end containing the two elements

$array[] = array($n, $obj);

Or if you want to have it indexed by some name instead

$array[] = array('number' => $n, 'mongoid' => $obj);
Comments