>  기사  >  백엔드 개발  >  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으로 문의하세요.