简体   繁体   中英

PHP get json data with json_decode

I'm new to PHP and try to echo out some data from json, but I got stucked in this.

It shows non of the data, but the data is there. The var_dump() shows it to me.

Probably I don't use the array correctly, but I can't find what's wrong. I've this code,

I request some data which I gathered with knockout.js

Knockout gives me a json (as show below)

$json = $_REQUEST[seats];

echo 'requested data raw '. "<br>".$json;
$data = json_decode($json, true);

echo "<br>".'var_dump '. "<br>";
var_dump($data);

foreach ($data  as $optie ) {
    echo "name = " . $optie->name . "<br>";
    echo "optie  = " . $optie->optieName . "<br>";
    echo "prijs    = " . $optie->prijs . "<br>";
}

This is my JSON:

[
    {
        "name": "Naam 1",
        "optie": {
            "optieName": "Make_up",
            "prijs": 9.95
        },
        "PrijsFormated": "Euro: 9.95"
    },
    {
        "name": "Naam 2",
        "optie": {
            "optieName": "Handverzorging",
            "prijs": 12.95
        },
        "PrijsFormated": "Euro: 12.95"
    }
]

You should use such loop:

foreach ($data  as $optie ) {
    echo "name = " . $optie['name'] . "<br>";
    echo "optie  = " . $optie['optie']['optieName'] . "<br>";
    echo "prijs    = " . $optie['optie']['prijs']. "<br>";
}

Because using json_decode() with second parameter as true you have created associative array - documentation .

If you would like to access data as object, you should use:

$data = json_decode($json);

instead of

$data = json_decode($json, true);

and then you should use the following loop:

foreach ($data  as $optie ) {
    echo "name = " . $optie->name . "<br>";
    echo "optie  = " . $optie->optie->optieName . "<br>";
    echo "prijs    = " . $optie->optie->prijs. "<br>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM