我只是不了解在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.
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
)
)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句