查看: 574|回复: 0

[PHP代码] php利用嵌套数组拼接与解析json的方法

发表于 2017-11-26 10:00:12

利用嵌套数组 拼接混合json -包含对象数组

  1. <?php
  2. // 自 PHP 5.4 起
  3. $array = [
  4. "status" => "0",
  5. "message" => "ok",
  6. "arr"=> []
  7. ];
  8. class Person {
  9. public $name;
  10. public $age;
  11. //定义一个构造方法初始化赋值
  12. public function __construct($name,$age) {
  13. $this->name=$name;
  14. $this->age=$age;
  15. }
  16. }
  17. for($i=0;$i<10;$i++)
  18. {
  19. $p=new Person("ren",$i);
  20. $array["arr"][]=$p;
  21. }
  22. //var_dump($array);
  23. echo json_encode($array);
  24. ?>
复制代码

php利用嵌套数组 解析混合json 包含对象数组

  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. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
  20. $web=json_decode($s);
  21. $arr=json_to_array($web);
  22. echo "<pre>";
  23. print_r($arr);
  24. echo "</pre>";
  25. /************************************************************************
  26. ************************************************************************/
  27. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
  28. $web=json_decode($s);
  29. echo '网站名称:'.$web->webname.'<br />网址:'.$web->url.'<br />联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;
  30. echo '<br /><br />';
  31. /************************************************************************
  32. ************************************************************************/
  33. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
  34. $web=json_decode($s);
  35. echo json_encode($web);
  36. $mys='{"status":"0","message":"ok","arr":[{"name":"ren","age":0},{"name":"ren","age":1},{"name":"ren","age":2},
  37. {"name":"ren","age":3},{"name":"ren","age":4},{"name":"ren","age":5},{"name":"ren","age":6},{"name":"ren","age":7},
  38. {"name":"ren","age":8},{"name":"ren","age":9}]}';
  39. $myweb=json_decode($mys);
  40. echo $myweb->status;
  41. for($i=0;$i<10;$i++)
  42. {
  43. echo $myweb->arr[$i]->age;
  44. echo '<br /><br />';
  45. }
  46. ?>
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条