Dean219 Dean219 - 1 year ago 282
PHP Question

Cannot use object of type MongoId as array

Im having a problem printing out the values inside a 2d array using echo, it works prefectly using print_r:


The result of which is :

Array ( [0] => MongoId Object
( [$id] => 57a789b7ce2350b40e000029 ) [1] => MongoId Object
( [$id] => 57a72d35ce2350681200002b ) [2] => 3 )

However when i try to access the values using:

echo $similar[0][1];
echo $similar[0][0];

I get the error : 'Cannot use object of type MongoId as array'

I have also tried different types of loops from here incase the error was triggered by accessing the values specifically by element number, however i got the same error and im unsure why. Any help would be appreciated :)

Answer Source

Since $similar[0] is an MongoId object, and want to access its $id then you must use $similar[0]->{'$id'})

in your example elements 0 and 1 are MongoId objects, while element 2 is an integer of 3.

So this is how you print them all

echo $similar[0]->{'$id'}) # gives 57a789b7ce2350b40e000029
echo $similar[1]->{'$id'}) # gives 57a72d35ce2350681200002b
echo $similar[2] # gives 3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download