我有以下格式的文档:
"_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循环中的echo部分。我发现了有关如何使用旧版驱动程序执行此操作的信息,而对于新版驱动程序则未找到任何信息。任何帮助将不胜感激。
答案 0 :(得分:1)
对象的products
部分是一个数组,还需要循环遍历。试试这个:
foreach ($row as $item) {
foreach ($item->products as $product) {
echo $product->name;
}
}