Reputation: 37
I have a document in the following format:
"_id" : ObjectId("5c6f16d9b4a523195c007ecb"),
"customerId" : "5c6dba6fb4a5231878007845",
"products" : [
{
"id" : "5c6c5b52dac9902ca917c98b",
"name" : "Black Starry Mug"
}
]
What I am trying to do is retrieve the name from products.
<?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);
}
The problem comes from the echo part in the foreach loop. I have found information on how to do this with the legacy driver but nothing with the new one. Any help would be greatly appreciated.
Upvotes: 0
Views: 314
Reputation: 147246
The products
part of your object is an array that you need to loop over as well. Try this:
foreach ($row as $item) {
foreach ($item->products as $product) {
echo $product->name;
}
}
Upvotes: 1