mongodb 如何使用 PHP 获取 MongoID 的字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7861332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get the string value of a MongoID using PHP?
提问by SomethingOn
After doing an insert I want to pass the object to the client using json_encode(). The problem is, the _id value is not included.
执行插入后,我想使用 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);
回答by John Pancoast
Believe this is what you're after.
相信这就是你所追求的。
$widget['_id']->{'$id'};
Something like this.
像这样的东西。
$widget = array('text' => 'Some text');
$this->mongo->db->insert($widget);
$widget['widgetId'] = $widget['_id']->{'$id'};
echo json_encode($widget);
回答by meltix
You can also use:
您还可以使用:
(string)$widget['_id']
回答by Rafael Guimar?es
correct way is use ObjectId from MongoDB:
正确的方法是使用 MongoDB 中的 ObjectId:
function getMongodbIDString($objectId){
$objectId = new \MongoDB\BSON\ObjectId($objectId);
return $objectId->jsonSerialize()['$oid'];
}
and do not cast the objectId like (string) $row['_id']
or $row->_id->{'$oid'}
并且不要像(string) $row['_id']
或$row->_id->{'$oid'}
回答by Abilash
I used something similar:
我使用了类似的东西:
(string)$widget->_id
回答by Mahdi Bagheri
I used something similar if object:
我使用了类似的 if 对象:
$widget->_id->{'$oid'}
or
或者
(string)$widget->_id
or array :
或数组:
$widget['id']->{'$oid'}
(string)$widget['_id']