1 var obj={"a":"v","b":"x"}; //这表示变量obj是一个对象,它有两个属性:a和b,属性值分别是:v和x. 2 var arr=["v","x"]; //这表示变量arr是一个数组,它有两一元素,索引分别是0和1,值分别是:v和x.
1 <?php 2 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 3 var_dump(json_decode($json)); 4 var_dump(json_decode($json, true)); 5 /*以上例程会输出: 6 object(stdClass)#1 (5) { 7 ["a"] => int(1) 8 ["b"] => int(2) 9 ["c"] => int(3) 10 ["d"] => int(4) 11 ["e"] => int(5) 12 } 13 array(5) { 14 ["a"] => int(1) 15 ["b"] => int(2) 16 ["c"] => int(3) 17 ["d"] => int(4) 18 ["e"] => int(5) 19 }*/
20 ?>
1 <?php 2 $json_string='{"id":1,"name":"mike","country":"usa","office":["microsoft","oracle"]} '; 3 $obj=json_decode($json_string); 4 //可以使用以下的方法来输出和访问 5 echo $obj->name; //displays mike 6 echo $obj->office[0]; //displays microsoft 7 ?>
1 $json='{"item1":{"item11":{"n":"chenling","m":"llll"},"sex":"男","age":"25"},"item2":{"item21":"ling","sex":"女","age":"24"}}'; 2 $J=json_decode($json); 3 print_r($J); 4 /*stdClass Object( 5 [item1] => stdClass Object( 6 [item11] => stdClass Object( 7 [n] => chenling 8 [m] => llll 9 ) 10 [sex] => 男 11 [age] => 25 12 ) 13 [item2] => stdClass Object( 14 [item21] => ling 15 [sex] => 女 16 [age] => 24 17 ) 18 )*/
要取得了值是chenling的那个属性,则应该这样访问:$J->item1->item11->n; //这将取得属性n的值:chenling
1 $json='{"item1":[{"name":[{"chen":"chenling","ling":"chenli"}],"sex":"男","age":"25"}{"name":"sun","sex":"女","age":"24"}]}'; 2 $J=json_decode($json); 3 print_r($J); 4 /*stdClass Object( 5 [item1] => Array( 6 [0] => stdClass Object( 7 [name] => Array( 8 [0] => stdClass Object( 9 [chen] => chenling 10 [ling] => chenli 11 ) 12 ) 13 [sex] => 男 14 [age] => 25 15 ) 16 [1] => stdClass Object( 17 [name] => sun 18 [sex] => 女 19 [age] => 24 20 ) 21 ) 22 )*/
1 $json='[["item1","item11"],["n","chenling"],["m","llll"]]'; 2 $J=json_decode($json); 3 print_r($J); 4 /*Array( 5 [0] => Array( 6 [0] => item1 7 [1] => item11 8 ) 9 [1] => Array( 10 [0] => n 11 [1] => chenling 12 ) 13 [2] => Array( 14 [0] => m 15 [1] => llll 16 ) 17 )*/
要取得了值是chenling的那个元素,则应该这样访问: $J[0][1];//这将取得元素值chenling的那个元素,但是用这种方式有一个缺点,就是无法用字符串作为索引,只能用数字,用完全对象的形式可以解决这个问题,其实这种访问形式就是数组的访问方式,相当于访问一个2维数组。