代码之家  ›  专栏  ›  技术社区  ›  Oscar Godson

MongoDB PHP:如何使用JSON提要获取ObjectId?(空白)

  •  5
  • Oscar Godson  · 技术社区  · 16 年前

    我通过GridFS存储一个文件并保存id,如下所示:

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

    目标ID(“4cbe9afe460890b774110000”)

    如果我这样做是为了创建一个JSON提要,这样我就可以为我的应用程序获取信息“file”是空的。。。这是为什么?:

    foreach($cursor as $item){
                $return[$i] = array(
                    'name'=>$item['name'],
                    'description'=>$item['description'],
                    'file'=>$item['file']
                );
                $i++;
            }
            echo json_encode($return);
    

    foreach($cursor as $item){
    echo $item['file'];
    }
    

    把它拿回来?

    哦,以下是提要返回的内容:

    [{"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":{}}]
    
    2 回复  |  直到 9 年前
        1
  •  5
  •   JochenJung    16 年前

    不确定,但也许

    echo json_encode($return, JSON_FORCE_OBJECT);
    

    是你需要做的。

    $item['file'] 至utf8

    utf8_encode($item['file']);
    

    在将其分配给 $return

        2
  •  1
  •   kris    16 年前

    Mongoid将其值隐藏在一个不可见的字段中。它没有可见的字段,因此没有任何内容可以转换为JSON,因此 {} . 如果你想让json_encode做“正确的”事情,投票给 http://jira.mongodb.org/browse/PHP-154 .

    回显MongoId会将其转换为字符串,这就是它行为不同的原因。

    推荐文章