-1

I've been trying to parse this JSON code (It's $customer_cart['products'] output):

{
    "Bag0145cm":{
        "name":"Pizza",
        "code":"Bag0145cm",
        "price":"9.50",
        "size":"45cm",
        "short_desc":"Shortdesc",
        "quantity":"1",
        "image":"IMG"
    },
    "Laptop0135cm":{
        "name":"Pizza2",
        "code":"Laptop0135cm",
        "price":"8.00",
        "size":"35cm",
        "short_desc":"Shortdesc",
        "quantity":"1",
        "image":"IMG"
    }
}

I'd like to get output all listed product names like this:

Pizza
Pizza2

I've tried this kind of code but getting foreach error

$array = json_decode($customer_cart['products'], true);

foreach($array as $product) {
    echo $product->name;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2534787
  • 115
  • 1
  • 7
  • Have you tried `echo $product['name'];` instead of `echo $product->name;`? – Definitely not Rafal Dec 10 '20 at 12:33
  • For future reference: when you're getting an error, include it in the question. It'll help us identify your problem quicker. Also, make sure to [look for it first](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/26572398#26572398). – El_Vanja Dec 10 '20 at 12:38

2 Answers2

0

This should help

$array = json_decode($customer_cart['products'], true);

foreach($array as $product) {
    echo $product['name'];
}

json_decode with "true" flag will return you associative array https://www.php.net/manual/en/function.json-decode.php

Alex
  • 75
  • 1
  • 1
  • 9
0

Looking at your code you have passed true as the second parameter to json_decode(), meaning it will be returned as an associative array, not an object.

Try using this instead:


$array = json_decode($customer_cart['products'], true);

foreach($array as $product) {
    echo $product['name'];
}

Notice that I'm using $product['name'] instead of $product->name, as we are dealing with an array, not an object.