2013-10-20 26 views
2

我簡直不明白在PHP中訪問JSON數據的語法。我一直在擺弄這一段時間。我太懂javascript了。不明白在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. 
+6

'的var_dump($ soundType);' – CBroe

+0

$ soundType是一個對象,嘗試用$ soundType [ '合成器'] [ 'synth_name'] – sensorario

+0

'回聲

' . print_r($patchDataJSON, true) . '
';' –

回答

0

json_decode返回對應於JSON結構的嵌套PHP數組。 (當通過true作爲第二個參數,否則返回PHP對象)。

要打印它,使用var_dumpprint_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 
       ) 
     ) 
)