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 ) )

  • 1
    Your `$json` is an object, and not an array, requiring `->` instead of `[]`. Please post `print_r($json)` so we can see its contents. – Michael Berkowski Apr 17 '14 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. – Michael Berkowski Apr 17 '14 at 17:38
  • possible duplicate of [Cannot use object of type stdClass as array?](http://stackoverflow.com/questions/6815520/cannot-use-object-of-type-stdclass-as-array) – Michael Berkowski Apr 17 '14 at 17:40

2 Answers2

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>';
    }

?>
jackfrankland
  • 2,052
  • 1
  • 13
  • 11
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
}
serakfalcon
  • 3,501
  • 1
  • 22
  • 33