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

问题描述 投票:10回答:5

插入后,我想使用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);
mongodb mongodb-php
5个回答
43
投票

相信这就是您所追求的。

$widget['_id']->{'$id'};

这样的事情。

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

21
投票

您也可以使用:

(string)$widget['_id']

2
投票

我使用了类似的东西:

(string)$widget->_id

1
投票

我使用类似的if对象:

$widget->_id->{'$oid'}

(string)$widget->_id

或数组:

$widget['id']->{'$oid'}
(string)$widget['_id']

1
投票

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

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

并且不要像(string) $row['_id']$row->_id->{'$oid'}那样投射objectId

© www.soinside.com 2019 - 2024. All rights reserved.