教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP JSON转数组

PHP JSON转数组

发布时间:2015-01-06   编辑:jiaochengji.com
本文为大家介绍在PHP中如何将JSON转成数组,而PHP解析JSON的两个函数:json_decode()和json_encode()。

本文为大家介绍在PHP中如何将JSON转成数组,而PHP解析JSON的两个函数:json_decode()和json_encode()。
 

复制代码 代码如下:

<?php
$s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';
$web=json_decode($s); //将字符转成JSON
$arr=array();
foreach($web as $k=>$w) $arr[$k]=$w;

前三行可以用$web=json_decode($s,true)代替;

print_r($arr);
?>
 

上面代码中,已经将一个JSON对象转成了一个数组,可是如果是嵌套的JSON,上面的代码显然无能为力了,那么我们写一个函数解决嵌套JSON,
 

复制代码 代码如下:

<?php
function json_to_array($web){
$arr=array();
foreach($web as $k=>$w){
    if(is_object($w)) $arr[$k]=json_to_array($w); //判断类型是不是object
    else $arr[$k]=$w;
}
return $arr;
}

$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
$arr=json_to_array($web);

//上一行可以用$web=json_decode($s,true)代替;
print_r($arr);
?>

自定义的json_to_array()方法可以将任何嵌套的JSON转成数组。

您可能感兴趣的文章:
php数组转json
PHP JSON转数组
php如何将数组转js数组
php中怎么把json转成对象数组
php如何将json文本转换成数组
PHP怎么把JSON转换成数组?
php如何转json
jquery中调用php json函数的方法分享
接口返回数据用xml好还是json理解
php可以如何处理json串

[关闭]
~ ~