在PHP中,可以使用json_encode()
和json_decode()
函數(shù)對(duì)JSON數(shù)據(jù)進(jìn)行序列化和反序列化。
$data = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
// 使用json_encode()函數(shù)將數(shù)組轉(zhuǎn)換為JSON字符串
$json_string = json_encode($data);
echo $json_string; // 輸出:{"name":"John","age":30,"city":"New York"}
$json_string = '{"name":"John","age":30,"city":"New York"}';
// 使用json_decode()函數(shù)將JSON字符串轉(zhuǎn)換為數(shù)組
$array = json_decode($json_string, true);
print_r($array); // 輸出:Array ( [name] => John [age] => 30 [city] => New York )
// 使用json_decode()函數(shù)將JSON字符串轉(zhuǎn)換為對(duì)象
$object = json_decode($json_string);
echo $object->name; // 輸出:John
注意:在使用json_decode()
函數(shù)時(shí),第二個(gè)參數(shù)設(shè)置為true
表示將JSON字符串轉(zhuǎn)換為關(guān)聯(lián)數(shù)組;如果不設(shè)置或設(shè)置為false
,則將JSON字符串轉(zhuǎn)換為對(duì)象。