PHP產生嵌套JSON解決思路_PHP教程

來源:互聯網
上載者:User
  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":"標題" } ]}

http://www.bkjia.com/PHPjc/820425.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/820425.htmlTechArticlePHP產生嵌套JSON ({ aa: [ { Id: 0, title: 標題, }, { Id: 1, title: 標題, } ], bb:[ { ... }, { .... } ] }) PHP如何產生這種嵌套的JSON ------解決方案--------------...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.