0

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.

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If I could give more than 1 vote I would. Thanks a million!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.