PHP用json_decode获取json数据

时间:2014-08-06 07:24:15

标签: php json knockout.js

我是PHP的新手并试图回应json中的一些数据,但我对此感到困惑。

它显示非数据,但数据存在。 var_dump()显示给我。

可能我没有正确使用阵列,但我无法找到错误。我有这段代码,

我要求使用knockout.js

收集一些数据

Knockout给了我一个json(如下所示)

$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>";
}

这是我的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"
    }
]

1 个答案:

答案 0 :(得分:2)

你应该使用这样的循环:

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

因为将json_decode()与第二个参数true一起使用,您创建了关联数组 - documentation

如果您想要将数据作为对象访问,则应使用:

$data = json_decode($json);

而不是

$data = json_decode($json, true);

然后你应该使用以下循环:

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