php中json數(shù)據(jù)的序列化與反序列化

PHP
小樊
87
2024-08-27 05:56:10

在PHP中,可以使用json_encode()json_decode()函數(shù)對(duì)JSON數(shù)據(jù)進(jìn)行序列化和反序列化。

  1. 序列化(將數(shù)組或?qū)ο筠D(zhuǎn)換為JSON字符串):
$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"}
  1. 反序列化(將JSON字符串轉(zhuǎn)換為數(shù)組或?qū)ο螅?/li>
$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ì)象。

0