首頁  >  文章  >  後端開發  >  利用php嵌套數組拼接並解析json

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

不言
不言原創
2018-06-13 17:11:242663瀏覽

本篇主要介紹了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=&#39;{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}&#39;;  
//将字符转成JSON  
$web=json_decode($s);  
$arr=array();  
foreach($web as $k=>$v)  
  $arr[$k]=$v;  
echo "<pre class="brush:php;toolbar:false">";  
print_r($arr);  
echo "
"; $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 "
";  
print_r($arr);  
echo "
"; /************************************************************************ ************************************************************************/ $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}'; $web=json_decode($s); echo '网站名称:'.$web->webname.'
网址:'.$web->url.'
联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail; echo '

'; /************************************************************************ ************************************************************************/ $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 '

'; } ?>

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

PHP CURL CURLOPT的參數說明

如何實作PHP根據陣列的值進行分組

########################################################## ######

以上是利用php嵌套數組拼接並解析json的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn