2

I simply do not understand the syntax for accessing JSON data in PHP. I've been fiddling about with this for awhile . I'm too javascript-ish to understand.

$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.
4

1 回答 1

0

json_decode返回对应于 JSON 结构的嵌套 PHP 数组。(当作为第二个参数传递时true,否则返回 PHP 对象)。

要打印它,请使用var_dumpor 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
                )
        )
)
于 2013-10-20T18:45:44.070 回答