如何使用PHP获取MongoID的字符串值?

Som*_*gOn 10 mongodb mongodb-php

执行插入后,我想使用json_encode()将对象传递给客户端.问题是,_id值不包括在内.

$widget = array('text' => 'Some text');

$this->mongo->db->insert($widget);


If I echo $widget['_id'] the string value gets displays on the screen, but I want to do something like this:

$widget['widgetId'] = $widget['_id']->id;


So I can do json_encode() and include the widget id:

echo json_encode($widget);
Run Code Online (Sandbox Code Playgroud)

Joh*_*ast 43

相信这就是你所追求的.

$widget['_id']->{'$id'};
Run Code Online (Sandbox Code Playgroud)

像这样的东西.

$widget = array('text' => 'Some text');
$this->mongo->db->insert($widget);
$widget['widgetId'] = $widget['_id']->{'$id'};
echo json_encode($widget);
Run Code Online (Sandbox Code Playgroud)

  • 参考这里:http://php.net/manual/en/class.mongoid.php.我更喜欢自己下面的(字符串)类型转换,但在问题发生时我使用的是文档中概述的方法. (2认同)

小智 21

您还可以使用:

(string)$widget['_id']
Run Code Online (Sandbox Code Playgroud)


Raf*_*ães 5

正确的方法是使用 MongoDB 中的 ObjectId:

function getMongodbIDString($objectId){
    $objectId = new \MongoDB\BSON\ObjectId($objectId);
    return $objectId->jsonSerialize()['$oid'];
}
Run Code Online (Sandbox Code Playgroud)

并且不要像(string) $row['_id']$row->_id->{'$oid'}