0

I'm trying to loop through my nested JSON and print the results but I get the aforementioned error when I try.

<?php

        $json = json_decode($orderItems);

        foreach ($json as $key) {

            ?><p>Product: <?php echo $json[$key] -> {'name'}; ?> | Quantity: <?php echo $json[$key] -> {'quantity'}; ?></p><?php

        }

    ?>

print_r($json)

stdClass Object ( [Tom] => stdClass Object ( [name] => Tom [quantity] => 3 ) [Harry] => stdClass Object ( [name] => Harry [quantity] => 1 ) )

3
  • 1
    Your $json is an object, and not an array, requiring -> instead of []. Please post print_r($json) so we can see its contents. Commented Apr 17, 2014 at 17:38
  • Or pass true as the second parameter to json_decode() to force it into an associative array instead of an anonymous object. Commented Apr 17, 2014 at 17:38
  • possible duplicate of Cannot use object of type stdClass as array? Commented Apr 17, 2014 at 17:40

2 Answers 2

3

You are referencing your $json variable as a mixture of an associative array and an object. Have a look at the following code:

<?php

    // return an assoc array
    $json = json_decode($orderItems, true);

    foreach ($json as $orderItem) {
        echo '<p>Product: ' . $orderItem['name'] . ' | ';
        echo 'Quantity: ' . $orderItem['quantity'] . '</p>';
    }

?>
Sign up to request clarification or add additional context in comments.

Comments

0

foreach loops don't work that way, and php has different syntax then that... what you are calling $key is actually each element in the array.

what you're looking for is probably something like:

foreach($json as $element) {
    ?><p>Product: <?php echo $element['name']; ?> | Quantity: <?php echo $element['quantity']; ?></p><?php
}

Comments

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.