在 PHP 中,json_encode
函数可以很好地处理嵌套数组。它会将数组转换成 JSON 对象,包括处理多维数组。下面是一个例子:
<?php
$nestedArray = array(
"name" => "John",
"age" => 30,
"city" => "New York",
"hobbies" => array(
"reading" => "PHP",
"traveling" => "USA",
"sports" => array(
"basketball" => "NBA",
"football" => "NFL"
)
)
);
$jsonResult = json_encode($nestedArray, JSON_PRETTY_PRINT);
echo $jsonResult;
?>
上述代码会输出以下 JSON 字符串:
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": {
"reading": "PHP",
"traveling": "USA",
"sports": {
"basketball": "NBA",
"football": "NFL"
}
}
}
json_encode
的第二个参数 JSON_PRETTY_PRINT
可选,它会将 JSON 字符串格式化为易读的形式。如果不使用这个参数,输出的 JSON 字符串将不会格式化。