How do you get the string value of a MongoID using PHP?

余生颓废 提交于 2019-12-03 09:30:21

问题


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.

$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);

回答1:


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);



回答2:


You can also use:

(string)$widget['_id']



回答3:


I used something similar:

(string)$widget->_id



回答4:


correct way is use ObjectId from MongoDB:

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'}




回答5:


I used something similar if object:

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

or

(string)$widget->_id

or array :

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


来源:https://stackoverflow.com/questions/7861332/how-do-you-get-the-string-value-of-a-mongoid-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!