创星网络[分享知识 传递快乐]

标题: 用php对json数据进行解析,获取各字段格式 [打印本页]

作者: luinstein    时间: 2012-10-23 15:32
标题: 用php对json数据进行解析,获取各字段格式
自己写的一段代码。
  1. <?php
  2. /**
  3. * by luinstein@cxweb.com.cn 2012-05-30 对json数据进行解析,获取各字段格式,适用于接口文档的数据类型显示
  4. */
  5. $json = "
  6. {
  7.     \"count\": 1,
  8.     \"list\": [
  9.         {
  10.             \"id\": 1,
  11.             \"title\": \"t\",
  12.             \"photos\": [
  13.                 {
  14.                     \"url\": \"http://www.cxweb.com.cn/static/image/common/logo.png\"
  15.                 },
  16.                 {
  17.                     \"url\": \"http://www.cxweb.com.cn/data/attachment/common/9f/common_56_icon.jpg\"
  18.                 }
  19.             ]
  20.         },
  21.         {
  22.             \"id\": 2,
  23.             \"title\": \"t2\",
  24.             \"photos\": []
  25.         }
  26.     ]
  27. }
  28. ";
  29. $res = json_decode($json,true);
  30. $new_r = getFiled($res);
  31. $new_r = clearP($new_r);
  32. print_r($new_r);

  33. function clearP($new_r){
  34.         foreach ($new_r as $k=>$v){               
  35.                 unset($new_r[$k]['p']);
  36.                 if($new_r[$k]['p_new']){                        
  37.                         $new_r[$k]['p_new'] = clearP($new_r[$k]['p_new']);
  38.                 }
  39.         }
  40.         return $new_r;
  41. }

  42. function getFiled($res){
  43.         $new_r = array();
  44.         $i = 0;
  45.         foreach ($res as $k=>$v){
  46.                
  47.                 if(is_numeric($k)&&$k>0){
  48.                         continue;
  49.                 }
  50.                 if(is_array($v)){        
  51.                         $new_r[$i]['key']=$k;
  52.                         $new_r[$i]['data_type'] = gettype($v);               
  53.                         $new_r[$i]['p'] = getFiled($v);
  54.                         $new_r[$i]['p_new'] = $new_r[$i]['p'][0]['p'];
  55.                 }else{
  56.                         $new_r[$i]['key']=$k;
  57.                         $new_r[$i]['data_type'] = gettype($v);
  58.                 }
  59.                 $i++;
  60.         }
  61.         return $new_r;
  62. }
复制代码





欢迎光临 创星网络[分享知识 传递快乐] (http://bbs.cxweb.com.cn/) Powered by Discuz! X3