一、json_encode() 對變量進行json編碼
- 語法:json_encode($value[,$options=0])
-
注意: 1、$value為要編碼的值,且該函數只對utf8編碼的數據有效;
2、options:由以下常量組成的二進制掩碼:json_hex_quot, json_hex_tag, json_hex_amp, json_hex_apos,json_numeric_check,json_pretty_print, json_unescaped_slashes, json_force_object;
3、第二個參數一般不需要;
4、json數據其實就是一個string,可以用var_dump()打印出來看數據類型;
5、執行成功返回json數據,否則返回false。
示例:
1
2
3
|
$book = array ( 'a' => 'xiyouji' , 'b' => 'sanguo' , 'c' => 'shuihu' , 'd' => 'hongloumeng' ); $json = json_encode( $book ); echo $json ; |
瀏覽器打印出的結果如下:
{"a":"xiyouji","b":"sanguo","c":"shuihu","d":"hongloumeng"}
二、json_decode() 對json數據進行解碼,轉換為php變量
- 語法:json_decode($json[,$assoc=false[,$depth=512[,$options=0]]])
-
注意:1、$json 為待解碼的數據,必須為utf8編碼的數據;
2、$assoc 值為true時返回數組,false時返回對象;
3、$depth 為遞歸深度;
4、$option二進制掩碼,目前只支持 json_bigint_as_string;
5、一般只用前面兩個參數,如果要數據類型的數據要加一個參數true。
示例:
1
2
3
4
5
6
7
|
$book = array ( 'a' => 'xiyouji' , 'b' => 'sanguo' , 'c' => 'shuihu' , 'd' => 'hongloumeng' ); $json = json_encode( $book ); $array = json_decode( $json ,true); $obj = json_decode( $json ); var_dump( $array ); var_dump( $obj ); |
瀏覽器打印出的結果如下:
array(4) { ["a"]=> string(7) "xiyouji" ["b"]=> string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=> string(11) "hongloumeng" }
object(stdclass)#2 (4) { ["a"]=> string(7) "xiyouji" ["b"]=> string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=> string(11) "hongloumeng" }
兩個結果看起來沒多大區別,但調用里面的元素時,array和obj的方式是不同的。
1
2
3
4
5
6
7
8
|
$book = array ( 'a' => 'xiyouji' , 'b' => 'sanguo' , 'c' => 'shuihu' , 'd' => 'hongloumeng' ); $json = json_encode( $book ); $array = json_decode( $json ,true); $obj = json_decode( $json ); var_dump( $array [ 'b' ]); //調用數組元素 echo '<br/>' ; var_dump( $obj ->c); //調用對象元素 |
打印結果如下:
string(6) "sanguo" string(6) "shuihu"
到此這篇關于淺析php中json_encode與json_decode的區別的文章就介紹到這了,更多相關php json_encode與json_decode內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/yehuisir/p/11106944.html