大家好,我使用 MongoDB 的 find() 方法是这样的:
$cursor = $collection->find();
foreach($cursor as $doc) {
// do something....
}
没关系,但我的 _id 属性是自动生成的,所以当我使用上面的代码时 $doc[_id] is Object 但我需要一个字符串。
如何自动将其转换为字符串。不是这样的:
foreach($cursor as $doc) {
$doc['_id'] = (string)$doc['_id'];
}
最佳答案
为了自动将来自 MongoDB 驱动程序的任何结果的 ObjectId 转换为字符串,我使用了这个函数:
function convertMongoIds(array &$array){
foreach ($array as &$element){
if (is_array($element)){
convertMongoIds($element);
}else if (is_object($element) && get_class($element) == "MongoId"){
$element = (string) $element;
}
}
}
关于php - MongoDB:ObjectId 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8106517/