我根本不理解在PHP中访问JSON数据的语法。我已经习惯了这一段时间了。我太懂了。
$patchData = $_POST['mydata'];
$encoded = json_encode($patchData,true);
$patchDataJSON = json_decode($encoded,true);
/* what my JSON object looks like
{"patch_name":"whatever","sound_type":{
"synths":[
{"synth_name":"synth1","xpos":"29.99999725818634","ypos":"10.000012516975403"},
{"synth_name":"synth2","xpos":"1.999997252328634","ypos":"18.000012516975403"},
]
}
}
*/
$patchName = $patchDataJSON['patch_name']; // works!
$soundType = $patchDataJSON['sound_type']; // trying to access innards of JSON object. Does not work
echo $soundType; // Does not work.
答案 0 :(得分:0)
json_decode
返回与JSON结构对应的嵌套PHP数组。 (当传递true
作为第二个参数时,否则返回PHP对象。)
要进行打印,请使用var_dump
或print_r
:
$soundType = $patchDataJSON['sound_type'];
print_r($soundType);
要访问字段,请使用字符串或数字索引(取决于输入JSON):
$xpos = $soundType['synths'][0]['xpos'];
等。
一个简单的例子:
$jsonString = '{"foo": "bar", "baz": [{"val": 5}]}';
$decoded = json_decode($jsonString, true);
print_r($decoded);
这将输出:
Array
(
[foo] => bar
[baz] => Array
(
[0] => Array
(
[val] => 5
)
)
)