利用php嵌套數組拼接並解析json

來源:互聯網
上載者:User
本篇文章主要介紹了php利用嵌套數組拼接與解析json的方法,內容挺不錯的,現在分享給大家,也給大家做個參考。

利用嵌套數組 拼接混合json -包含對象數組

<?php  // 自 PHP 5.4 起 $array = [   "status" => "0",   "message" => "ok",   "arr"=> [] ];  class Person {    public $name;    public $age;      //定義一個構造方法初始化賦值    public function __construct($name,$age) {      $this->name=$name;      $this->age=$age;    }  }       for($i=0;$i<10;$i++) {   $p=new Person("ren",$i);    $array["arr"][]=$p; }  //var_dump($array);  echo json_encode($array);  ?>

php利用嵌套數組 解析混合json 包含對象數組

<?php  function json_to_array($web) {    $arr=array();    foreach($web as $k=>$v) {      if(is_object($v)) $arr[$k]=json_to_array($v); //判斷類型是不是object      else $arr[$k]=$v;    }    return $arr;  }  $s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';  //將字元轉成JSON  $web=json_decode($s);  $arr=array();  foreach($web as $k=>$v)    $arr[$k]=$v;  echo "<pre>";  print_r($arr);  echo "</pre>";    $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  $web=json_decode($s);  $arr=json_to_array($web);  echo "<pre>";  print_r($arr);  echo "</pre>";    /************************************************************************ ************************************************************************/  $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  $web=json_decode($s);  echo '網站名稱:'.$web->webname.'<br />網址:'.$web->url.'<br />連絡方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;  echo '<br /><br />';  /************************************************************************ ************************************************************************/  $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  $web=json_decode($s);  echo json_encode($web);    $mys='{"status":"0","message":"ok","arr":[{"name":"ren","age":0},{"name":"ren","age":1},{"name":"ren","age":2}, {"name":"ren","age":3},{"name":"ren","age":4},{"name":"ren","age":5},{"name":"ren","age":6},{"name":"ren","age":7}, {"name":"ren","age":8},{"name":"ren","age":9}]}';  $myweb=json_decode($mys);   echo $myweb->status;  for($i=0;$i<10;$i++) {  echo $myweb->arr[$i]->age;  echo '<br /><br />';  }  ?>

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.