繁体   English   中英

使用mongoDB和php驱动程序管理器从嵌套字段获取数据

[英]Getting data from nested fields using mongoDB and php driver manager

我有以下格式的文档:

 "_id" : ObjectId("5c6f16d9b4a523195c007ecb"),
 "customerId" : "5c6dba6fb4a5231878007845",
 "products" : [
         {
                 "id" : "5c6c5b52dac9902ca917c98b",
                 "name" : "Black Starry Mug"
         }
]

我正在尝试从产品中检索名称。

<?php
$customerId = $_GET["customer-id"];
$cart = json_decode($_GET["cart"]);
$manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter  = ['customerId' => $customerId];
$options = [];
$query = new MongoDB\Driver\Query($filter , $options);
try {
    $result = $manager->executeQuery('GameMerchandise.cart', $query);
    $row = $result->toArray();
    foreach ($row as $item) {
        echo $item->products->name;
   }
}catch(MongoDB\Driver\Exception\Exception $e) {
    die("Error communicating with database: " . $e);
}

问题来自foreach循环中的回显部分。 我已经找到了有关如何使用旧版驱动程序进行操作的信息,而对于新版驱动程序则没有任何信息。 任何帮助将不胜感激。

对象的products部分是一个数组,您还需要遍历该数组。 尝试这个:

foreach ($row as $item) {
    foreach ($item->products as $product) {
        echo $product->name;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM