Reputation: 12403
I am having a problem where I retrieving an ObjectID from a MongoDB database , but the '_id' value is always disappearing when ran though json_encode. All the other data in my array is present. My code is as such:
$data = array('_id' => new MongoDB\BSON\ObjectID(), 'title' => 'abc123');
//ID Is there!
print_r($data);
//ID IS EMPTTYy!!!
print_r(json_encode($data));
exit();
The results look like this:
Array ( [_id] => MongoDB\BSON\ObjectID Object ( [oid] => 56d9d2687e34d70d3a304c46 ) [title] => abc123 )
{"_id":{},"title":"abc123"}
At the very least, the _id should have an object or number in it. My question is what is stripping out the \MongoDB\BSON\ObjectID and how can I get it to stay?
Upvotes: 2
Views: 1369
Reputation: 1422
example code for @malarzm's answer:
$output = [];
foreach( $data as $key => $val){
$val->_id = strval($val->_id);
$output[$key] = $val;
}
echo json_encode( $output );
Upvotes: 0
Reputation: 2966
My question is what is stripping out the \MongoDB\BSON\ObjectID
json_encode
will encode only public
properties of encountered objects.
how can I get it to stay?
You could cast it to string before encoding.
Upvotes: 4