问题
I'm storing a file through GridFS and saving the id like so:
$file_id = $gridfs->storeUpload('texture');
$item = array(
'name'=>$_POST['name'],
'description'=>$_POST['description'],
'price'=>$_POST['price'],
'categories'=>$category_array,
'tags'=>$tag_array,
'file'=>$file_id
);
$collection->insert($item);
and through terminal and doing find() "file" returns: ObjectId("4cbe9afe460890b774110000")
If i do this to create a JSON feed so i can get info back for my application "file" is blank... why is this?:
foreach($cursor as $item){
$return[$i] = array(
'name'=>$item['name'],
'description'=>$item['description'],
'file'=>$item['file']
);
$i++;
}
echo json_encode($return);
The strange thing, to me, is why can I do:
foreach($cursor as $item){
echo $item['file'];
}
and get it back tho?
Oh, and here is what the feed returns:
[{"name":"Tea Stained Paper 1","description":"Grungy paper texture stained with tea and coffee.","file":{}},{"name":"Worn Metal 1","description":"A grooved, worn old metal texture","file":{}}]
回答1:
Not sure, but maybe
echo json_encode($return, JSON_FORCE_OBJECT);
is what you need to do.
It also could be, that you need to convert $item['file']
to utf8
utf8_encode($item['file']);
before assigning it to the $return
array.
回答2:
MongoIds keep their values tucked away in an invisible field. It has no visible fields, so there's nothing to convert to JSON, hence {}
. If you'd like to have json_encode do the "right" thing, vote for http://jira.mongodb.org/browse/PHP-154.
Echoing a MongoId converts it to a string, that's why it behaves differently.
来源:https://stackoverflow.com/questions/3975939/mongodb-php-how-do-i-get-objectid-with-a-json-feed-its-blank