php中json数据的序列化与反序列化

PHP
310
2024/8/27 6:31:04
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在PHP中,可以使用json_encode()json_decode()函数对JSON数据进行序列化和反序列化。

  1. 序列化(将数组或对象转换为JSON字符串):
$data = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);

// 使用json_encode()函数将数组转换为JSON字符串
$json_string = json_encode($data);

echo $json_string; // 输出:{"name":"John","age":30,"city":"New York"}
  1. 反序列化(将JSON字符串转换为数组或对象):
$json_string = '{"name":"John","age":30,"city":"New York"}';

// 使用json_decode()函数将JSON字符串转换为数组
$array = json_decode($json_string, true);

print_r($array); // 输出:Array ( [name] => John [age] => 30 [city] => New York )

// 使用json_decode()函数将JSON字符串转换为对象
$object = json_decode($json_string);

echo $object->name; // 输出:John

注意:在使用json_decode()函数时,第二个参数设置为true表示将JSON字符串转换为关联数组;如果不设置或设置为false,则将JSON字符串转换为对象。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: php分页功能如何实现