0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This looks like too much pain in the butt to just work with objects for the sake of it. I'll stick to arrays then :-) Thanks!
0

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

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.