json數組轉普通數組 普通數組轉json數組


1.json_decode() 

json_decode 
(PHP 5 >= 5.2.0, PECL json >= 1.2.0) 

json_decode — 對 JSON 格式的字符串進行編碼 

說明 
mixed json_decode ( string $json [, bool $assoc ] ) 
接受一個 JSON 格式的字符串並且把它轉換為 PHP 變量 

參數 

json 
待解碼的 json string 格式的字符串。 

assoc 
當該參數為 TRUE 時,將返回 array 而非 object 。 


返回值 
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned. 

 json_decode() 的例子 

<?php 
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
var_dump(json_decode($json)); 
var_dump(json_decode($json, true)); 
?> 

結果

object(stdClass)#1 (5) { 
["a"] => int(1) 
["b"] => int(2) 
["c"] => int(3) 
["d"] => int(4) 
["e"] => int(5) 
} 

array(5) { 
["a"] => int(1) 
["b"] => int(2) 
["c"] => int(3) 
["d"] => int(4) 
["e"] => int(5) 
} 

可以看出 json_decode($data,true)輸出的一個關聯數組,由此可知json_decode($data)輸出的是對象,而json_decode("$arr",true)是把它強制生成PHP關聯數組. 

2.json_encode() 

json_encode 
(PHP 5 >= 5.2.0, PECL json >= 1.2.0) 

json_encode — 對變量進行 JSON 編碼 

Report a bug 說明 
string json_encode ( mixed $value [, int $options = 0 ] ) 
返回 value 值的 JSON 形式 

Report a bug 參數 

value 
待編碼的 value ,除了resource 類型之外,可以為任何數據類型 

該函數只能接受 UTF-8 編碼的數據 

Report a bug 返回值 
編碼成功則返回一個以 JSON 形式表示的 string 或者在失敗時返回 FALSE 。 

json_encode() 例子

<?php 
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 

echo json_encode($arr); 
?>

結果

{"a":1,"b":2,"c":3,"d":4,"e":5} 

可以看出json_encode()和json_decode()是編譯和反編譯過程,注意json只接受utf-8編碼的字符,所以json_encode()的參數必須是utf-8編碼,否則會得到空字符或者null。

轉編碼格式用以下函數

<?php

$arr=iconv('gbk','utf-8',$arr);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM