本文实例分析了PHP针对JSON操作。分享给大家供大家参考。具体分析如下:
由于JSON可以在很多种程序语言中使用,所以我们可以用
5本文来源gao!daima.com搞$代!码#网#
搞代gaodaima码
来做小型数据中转,如:PHP输出JSON字符串供JavaScript使用等。在PHP中可以使用 json_decode() 由一串规范的字符串解析出 JSON对象,使用 json_encode() 由JSON 对象生成一串规范的字符串。
例:
<?php<br />$json = '{"a":1, "b":2, "c":3, "d":4, "e":5 }';<br />var_dump(json_decode($json));<br />var_dump(json_decode($json,true));
输出:
object(stdClass)#1 (5) {<br />["a"] => int(1)<br />["b"] => int(2)<br />["c"] => int(3)<br />["d"] => int(4)<br />["e"] => int(5)<br />}</p><p>array(5) {<br />["a"] => int(1)<br />["b"] => int(2)<br />["c"] => int(3)<br />["d"] => int(4)<br />["e"] => int(5)<br />}
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);<br />echo json_encode($arr);
输出:{“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}
1. json_decode(),字符转JSON,一般用在接收到Javascript 发送的数据时会用到。
<?php<br />$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","mail":"[email protected]","xx":"xxxxxxx"}}';<br />$web=json_decode($s);<br />echo '网站名称:'.$web->webname.'<br />网址:'.$web->url.'<br />联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;<br />?>
上面的例子中,我们首先定义了一个变量s,然后用json_decode()解析成JSON对象,之后可以按照JSON的方式去使用,从使用情况看,JSON和XML以及数组实现的功能类似,都可以存储一些相互之间存在关系的数据,但是个人觉得JSON更容易使用,且可以使用JSON和JavaScript实现数据共享。
2. json_encode(),JSON转字符,这个一般在AJAX 应用中,为了将JSON对象转化成字符串并输出给 Javascript 时会用到,而向数据库中存储时也会用到。
<?php<br />$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","mail":"[email protected]","xx":"xxxxxxx"}}';<br />$web=json_decode($s);<br />echo json_encode($web);<br />?>
二 .PHP JSON 转数组
<?php<br />$s='{"webname":"homehf","url":"www.homehf.com","qq":"123456789"}';<br />$web=json_decode($s); //将字符转成JSON<br />$arr=array();<br />foreach($web as $k=>$w) $arr[$k]=$w;<br />print_r($arr);<br />?>
上面的代码中,已经将一个JSON对象转成了一个数组,可是如果是嵌套的JSON,上面的代码显然无能为力了,那么我们写一个函数解决嵌套JSON,
<?php<br />$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","mail":"[email protected]","xx":"xxxxxxx"}}';<br />$web=json_decode($s);<br />$arr=json_to_array($web);<br />print_r($arr);</p><p>function json_to_array($web){<br />$arr=array();<br />foreach($web as $k=>$w){<br /> if(is_object($w)) $arr[$k]=json_to_array($w); //判断类型是不是object<br /> else $arr[$k]=$w;<br />}<br />return $arr;<br />}<br />?>
希望本文所述对大家的php程序设计有所帮助。