萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> PHP生成嵌套JSON解決思路

PHP生成嵌套JSON解決思路

   PHP生成嵌套JSON

  ({

  "aa": [

  {

  "Id": "0",

  "title": "標題",

  },

  {

  "Id": "1",

  "title": "標題",

  }

  ],

  "bb":[

  {

  ...

  },

  {

  ....

  }

  ]

  })

  PHP如何生成這種嵌套的JSON

  ------解決方案--------------------

  /** Json數據格式化

  * @param Mixed $data 數據

  * @param String $indent 縮進字符,默認4個空格

  * @return JSON

  */

  function jsonFormat($data, $indent=null){

  // 對數組中每個元素遞歸進行urlencode操作,保護中文字符

  array_walk_recursive($data, 'jsonFormatProtect');

  // json encode

  $data = json_encode($data);

  // 將urlencode的內容進行urldecode

  $data = urldecode($data);

  // 縮進處理

  $ret = '';

  $pos = 0;

  $length = strlen($data);

  $indent = isset($indent)? $indent : ' ';

  $newline = "n";

  $prevchar = '';

  $outofquotes = true;

  for($i=0; $i<=$length; $i++){

  $char = substr($data, $i, 1);

  if($char=='"' && $prevchar!=''){

  $outofquotes = !$outofquotes;

  }elseif(($char=='}' ------解決方案-------------------- $char==']') && $outofquotes){

  $ret .= $newline;

  $pos --;

  for($j=0; $j<$pos; $j++){

  $ret .= $indent;

  }

  }

  $ret .= $char;

  if(($char==',' ------解決方案-------------------- $char=='{' ------解決方案-------------------- $char=='[') && $outofquotes){

  $ret .= $newline;

  if($char=='{' ------解決方案-------------------- $char=='['){

  $pos ++;

  }

  for($j=0; $j<$pos; $j++){

  $ret .= $indent;

  }

  }

  $prevchar = $char;

  }

  return $ret;

  }

  /** 將數組元素進行urlencode

  * @param String $val

  */

  function jsonFormatProtect(&$val){

  if($val!==true && $val!==false && $val!==null){

  $val = urlencode($val);

  }

  }

  header('content-type:application/json;charset=utf8');

  $arr = array(

  'aa' => array(

  array(

  'Id' => 0,

  'title' => '標題'

  ), array( 'Id' => 1, 'title' => '標題' ), ), 'bb' => array( array( 'Id' => 2, 'title' => '標題' ), array( 'Id' => 3, 'title' => '標題' ), ));echo jsonFormat($arr);{ "aa":[ { "Id":"0", "title":"標題" }, { "Id":"1", "title":"標題" } ], "bb":[ { "Id":"2", "title":"標題" }, { "Id":"3", "title":"標題" } ]}

copyright © 萬盛學電腦網 all rights reserved