Home > php教程 > php手册 > body text

PHP数组和Json之间的转换详解

WBOY
Release: 2016-06-13 10:16:37
Original
1059 people have browsed it

在php中数组与json转换很简单,我们只要使用json_encode() 和 json_decode()。很容易理解,json_encode()就是将PHP数组转换成Json。相反,json_decode()就是将Json转换成PHP数组。

例如:

 代码如下 复制代码

$array = array("name" => "Eric","age" => 23);
 
echo json_encode($array);

程序将打印出 :

 {“name”:”Eric”,”age”:23}

再看下面的例子:

 代码如下 复制代码

$array = array(0 => "Eric", 1 => 23);
 
echo json_encode($array);

程序将打印出 :

["Eric",23]

这样就可以将 json 转换成数组形式了,key 保持原来格式 

 代码如下 复制代码

$json = ’{"name":"zhangsan","age":20,"sex":"nan"}’; 

print_r(json_decode($json,true)); 

这样的json数据解析后 就会成为下面这样的数组 


Array 

    [name] => zhangsan 
    [age] => 20 
    [sex] => nan 
)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!