2011-10-22 70 views
8

做了一个插入后,我想使用json_encode()将对象传递给客户端。问题是,_id值不包括在内。如何使用PHP获取MongoID的字符串值?

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

回答

41

相信这是你所追求的。

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

就是这样。

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

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

17

您还可以使用:

(string)$widget['_id'] 
1

我用类似的东西:

(string)$widget->_id

0

我使用了类似的东西,如果对象:

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

(string)$widget->_id 

或数组:

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