json_encode
是 PHP 中用于将数组或对象转换为 JSON 格式的函数。要处理数组,只需将要编码的数据作为参数传递给 json_encode
函数即可。以下是一些示例:
- 编码一个关联数组:
$array = array( "name" => "John", "age" => 30, "city" => "New York" ); $json = json_encode($array); echo $json; // 输出:{"name":"John","age":30,"city":"New York"}
- 编码一个多维数组:
$array = array( array("name" => "John", "age" => 30), array("name" => "Jane", "age" => 28) ); $json = json_encode($array); echo $json; // 输出:[{"name":"John","age":30},{"name":"Jane","age":28}]
- 编码一个包含数组作为值的关联数组:
$array = array( "names" => array("John", "Jane", "Doe"), "ages" => array(30, 28, 25) ); $json = json_encode($array); echo $json; // 输出:{"names":["John","Jane","Doe"],"ages":[30,28,25]}
json_encode
函数还可以接受其他可选参数,例如设置 JSON 格式化的选项。要了解更多关于 json_encode
的信息,可以查阅 PHP 官方文档:https://www.php.net/manual/en/function.json-encode.php