php json转换为嵌套数组array

[php] view plain copy
 
  1. <?php  
  2. function json_to_array($web) {  
  3.     $arr=array();  
  4.     foreach($web as $k=>$v) {  
  5.         if(is_object($v)) $arr[$k]=json_to_array($v);  //判断类型是不是object  
  6.         else $arr[$k]=$v;  
  7.     }  
  8.     return $arr;  
  9. }  
  10. $s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';  
  11. //将字符转成JSON  
  12. $web=json_decode($s);  
  13. $arr=array();  
  14. foreach($web as $k=>$v)  
  15.     $arr[$k]=$v;  
  16. echo "<pre>";  
  17. print_r($arr);  
  18. echo "</pre>";  
  19.   
  20. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  
  21. $web=json_decode($s);  
  22. $arr=json_to_array($web);  
  23. echo "<pre>";  
  24. print_r($arr);  
  25. echo "</pre>";  
  26.   
  27. /************************************************************************ 
  28. ************************************************************************/  
  29. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  
  30. $web=json_decode($s);  
  31. echo '网站名称:'.$web->webname.'<br />网址:'.$web->url.'<br />联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;  
  32. echo '<br /><br />';  
  33. /************************************************************************ 
  34. ************************************************************************/  
  35. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  
  36. $web=json_decode($s);  
  37. echo json_encode($web);  

 

posted @ 2016-12-20 17:15  天涯海角路  阅读(402)  评论(0)    收藏  举报