Question

While using Codeigniter and its built-in class Mongo, is it possible to get objects instead of arrays?

I'd rather access documents via $doc->id than $doc['id']. Thanks.

Was it helpful?

Solution

The PHP MongoDB lib will always return result as array. If you wish to work with objects instead of arrays you will need to handle conversion yourself. As converting to an object is not as easy as casting type you would have to write your own function to convert it to an object.

You could do something in a sense

$obj = new stdClass();

foreach($mongoResult as $key => $val){
    $obj -> $key = $val;
}

Obviously this will work on basic result sets. You would need to write a more sophisticated function to handle more complex arrays.

OTHER TIPS

I believe the issue has to do with how you are querying the database.

$this->db->query()->get->result();

Will give you objects.

$this->db->query()->get()->result_array(); 

Will give you arrays

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top