Heim  >  Artikel  >  Backend-Entwicklung  >  PHP操作JSON数据

PHP操作JSON数据

巴扎黑
巴扎黑Original
2016-11-21 14:19:351642Durchsuche

JSON 是一个轻量级的文本数据交换格式,他比 XML 更小、更快,更易解析,所以在PHP开发过程中,我们经常会用它来传递数据,本文UncleToo将个大家介绍一下PHP如何操作JSON数据

PHP操作JSON数据一般在AJAX中用的比较多,可以将JSON格式的数据传给AJAX,也可以将AJAX返回的JSON数据解析成我们需要的字符串。在PHP中可以使用 json_decode() 函数来解析JSON格式数据,使用 json_encode() 函数将字符串(数组)生成JSON格式。

先看示例:

示例1:

Php代码  

<?php  
$json = &#39;{"a":1, "b":2, "c":3, "d":4, "e":5 }&#39;;  
var_dump(json_decode($json));  
echo "<br/>";  
var_dump(json_decode($json,true));  
?>

 

输出:

object(stdClass)#1 (5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }

array(5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }

示例2:

 

Php代码  

<?php  
$arr = array (&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>4,&#39;e&#39;=>5);  
echo json_encode($arr);  
?>

 

输出:

{"a":1,"b":2,"c":3,"d":4,"e":5}

 

从示例1我们可以看到,用json_decode函数可以将JSON数据转换成数组,但是,如果JSON数据里又嵌套了JSON数据,那就不能直接这样写了,这里需要用自定义函数来实现将嵌套的JSON数据转换成数组。

示例:

 

Php代码  

<?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;  
}  
?>

 调用示例:

Php代码  

<?php  
$s=&#39;{"webname":"UncleToo","url":"www.uncletoo.com","menu":{"PHP":"1","DataBase":"2","Web":"3"}}&#39;;  
$web=json_decode($s);  
$arr=json_to_array($web);  
print_r($arr);  
?>

 

输出:

Array ( [webname] => UncleToo [url] => www.uncletoo.com [menu] => Array ( [PHP] => 1 [DataBase] => 2 [Web] => 3 ) )

以上就是PHP操作JSON数据的常用方法,大家如果有其他想法及方法可以跟UncleToo一起讨论。


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php 批量上传Nächster Artikel:PHP如何获取数组的键与值