如何使用PHP为JSON创建数组?
来源:藏色散人
发布时间:2019-03-19 14:28:04
阅读量:1184
PHP中有三种类型的数组:索引数组、关联数组、多维数组。我们将使用键值类型结构存储数据的关联数组。这些键将是一个字符串或整数,它将用作索引来搜索数组中相应的值。

json_encode函数用于将数组的值转换为JSON。这个函数是从PHP5中添加的。此外,你还可以根据你的需求对数组进行更多嵌套。你也可以使用此函数创建对象数组的数组。
与JSON一样,所有内容都存储为键值对,我们将把这些PHP数组的键值对转换为JSON, JSON可用于从REST API服务器发送响应。
下面是将数组转换为JSON的示例。
示例1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php
$arr = array (
array (
"name" => "Pankaj Singh" ,
"age" => "20"
),
array (
"name" => "Arun Yadav" ,
"age" => "21"
),
array (
"name" => "Apeksha Jaiswal" ,
"age" => "20"
)
);
echo json_encode( $arr );
|
输出:
1 2 3 | [{ "name" : "Pankaj Singh" , "age" : "20" },
{ "name" : "Arun Yadav" , "age" : "21" },
{ "name" : "Apeksha Jaiswal" , "age" : "20" }]
|
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php
$arr = array (
"first" => array (
"id" =>1,
"product_name" => "Doorbell" ,
"cost" =>199
),
"second" => array (
"id" =>2,
"product_name" => "Bottle" ,
"cost" =>99
),
"third" => array (
"id" =>3,
"product_name" => "Washing Machine" ,
"cost" =>7999
)
);
echo json_encode( $arr );
|
输出:
1 2 3 | { "first" :{ "id" :1, "product_name" : "Doorbell" , "cost" :199},
"second" :{ "id" :2, "product_name" : "Bottle" , "cost" :99},
"third" :{ "id" :3, "product_name" : "Washing Machine" , "cost" :7999}}
|