學習 JSON 類時,你可能會遇到形形色色的問題。本文將整理一些常見問題的解決方法與大家分享。現在經常需要用 PHP 與 JS 進行資料交互,其中最常用的就是 JSON 類,接下來我用自己的話談談這兩種語言之間的資料交互。
在 PHP 中,有 json_encode 與 json_decode 兩個方法:前者多用於把 PHP 陣列轉為 JSON 格式,如 {"a":"a1","b":"b1"};後者則把 JSON 格式轉回 PHP 物件,並可透過 $obj->a 的方式呼叫(若一時不理解別著急,看看下面的例子就明白了)。
以下是一個可以自己複製試看看的實例:
<?php
$string = array(
"num1" => "one",
"num2" => "two",
"num3" => array(
"num31" => "three_one",
"num32" => "three_two",
)
);
print_r($string);
echo "<br/>";
$json = json_encode($string);
echo $json;
echo "<br/>";
$fjson = json_decode($json);
print_r($fjson);
echo "<br/>";
echo $fjson->num3->num31; // 多層物件的屬性存取
echo "<br/>";
$arr = (array)$fjson; // 物件轉陣列
print_r($arr);
echo "<br/>";
$arr2 = (array)$fjson->num3;
print_r($arr2);
echo "<br/>";
echo "<script>alert($json.num3.num31)</script>";
?>
Array ( [num1] => one [num2] => two [num3] => Array ( [num31] => three_one [num32] => three_two ) )
{"num1":"one","num2":"two","num3":{"num31":"three_one","num32":"three_two"}}
stdClass Object ( [num1] => one [num2] => two [num3] => stdClass Object ( [num31] => three_one [num32] => three_two ) )
three_one
Array ( [num1] => one [num2] => two [num3] => stdClass Object ( [num31] => three_one [num32] => three_two ) )
Array ( [num31] => three_one [num32] => three_two )
以上就是對 JSON 類的介紹說明。透過這個例子,你應該能清楚看到 PHP 陣列如何轉為 JSON 字串、如何再轉回物件,以及如何透過 -> 逐層存取嵌套屬性、用型別轉換把物件還原為陣列。歡迎大家一起學習切磋。