php返回json数据并输出的简单实例

这里奉上一个php解析json数据,并输出的示例,供大家参考。
折叠PHP 代码
  1. <?php  
  2. echo '<h1>法一</h1>';  
  3. //假设以下数组是根据我们从数据库读取的数据生成的  
  4. $jarr=array('total'=>239,'row'=>array(  
  5.            array('code'=>'001','name'=>'中国','addr'=>'Address 11','col4'=>'col4 data'),  
  6.            array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'),  
  7.                                      )  
  8.            );  
  9. //法一:  
  10. $jobj=new stdclass();//实例化stdclass,这是php内置的空类,可以用来传递数据,由于json_decode后的数据是以对象数组的形式存放的,  
  11. //所以我们生成的时候也要把数据存储在对象中  
  12. foreach($jarr as $key=>$value){  
  13. $jobj->$key=$value;  
  14. }  
  15. print_r($jobj);//打印传递属性后的对象  
  16. echo '使用$jobj->row[0][\'code\']输出数组元素:'.$jobj->row[0]['code'].'<br>';  
  17. echo '编码后的json字符串:'.json_encode($jobj).'<br>';//打印编码后的json字符串  
  18.   
  19.   
  20. echo '<hr>';  
  21. //法二:  
  22. echo '<h1>法二</h1>';  
  23. echo '编码后的json字符串:';  
  24. echo $str=json_encode($jarr);//将数组进行json编码  
  25. echo '<br>';  
  26. $arr=json_decode($str);//再进行json解码  
  27. print_r($arr);//打印解码后的数组,数据存储在对象数组中  
  28. echo '使用$arr->row[0]->code输出数组元素:'.$arr->row[0]->code;  
  29.   
  30. ?>   

另外一个简单的例子,非常直观。

折叠PHP 代码
  1. <?php  
  2.   $json='[{"name":"qqdeliver","count":198,"average":119.8889},{"name":"load","count":259612,"average":141.9379},{"name":"gate","count":22480,"average":9.2209},{"name":"interact","count":40165,"average":429.3583},{"name":"save","count":2097845,"average":180.6606},{"name":"login","count":29239,"average":322.0906},{"name":"neighbour","count":24777,"average":368.9143},{"name":"updatesave","count":842358,"average":75.1193},{"name":"promotion","count":69417,"average":37.7616},{"name":"activity","count":22978,"average":5.4393},{"name":"message","count":49590,"average":172.3676},{"name":"admin","count":155,"average":750.3032},{"name":"qqpay","count":3078,"average":79.4916},{"name":"alliance","count":54091,"average":120.0409},{"name":"updates","count":189196,"average":54.6144},{"name":"friend","count":26259,"average":101.0704},{"name":"attack","count":8146,"average":205.2529}]';  
  3.   $obj=json_decode($json);  
  4.   //print_r($obj);  
  5.   foreach ( $obj as $unit ){  
  6.     echo $unit->name.'<br>';  
  7.   }  
  8. ?>  

 

Tags: php   json
cms大学,为帝国cms用户提供动力
Copyright © 2016 CmsDX.com All Rights Reserved.