MongoDB\BSON\ObjectID 迷失在 JSON 从 MongoDB 编码

MongoDB\BSON\ObjectID Lost In JSON Encode from MongoDB

我在从 MongoDB 数据库中检索 ObjectID 时遇到问题,但是当 运行 尽管 json_encode 时 '_id' 值总是消失。我数组中的所有其他数据都存在。我的代码是这样的:

$data = array('_id' => new MongoDB\BSON\ObjectID(), 'title' => 'abc123');

 //ID Is there!
 print_r($data);
 //ID IS EMPTTYy!!!
 print_r(json_encode($data));
 exit();

结果如下所示:

Array ( [_id] => MongoDB\BSON\ObjectID Object ( [oid] => 56d9d2687e34d70d3a304c46 ) [title] => abc123 ) 

{"_id":{},"title":"abc123"}

至少,_id 中应该有一个对象或数字。我的问题是什么在剥离 \MongoDB\BSON\ObjectID,我怎样才能让它留下来?

My question is what is stripping out the \MongoDB\BSON\ObjectID

json_encode 将仅对遇到的对象的 public 属性进行编码。

how can I get it to stay?

您可以在编码之前将其转换为字符串。

@malarzm 回答的示例代码:

$output = [];
foreach( $data as $key => $val){
    $val->_id = strval($val->_id);
    $output[$key] = $val;
}

echo json_encode( $output );