轉自:http://www.nowamagic.net/php/php_FunctionJsonEncode.phpphp
轉自:http://www.jb51.net/article/30489.htm前端
在 php 中使用 json_encode() 內置函數(php > 5.2)可使用得 php 中數據能夠與其它語言很好的傳遞而且使用它。
這個函數的功能是將數值轉換成json數據存儲格式。
<?php
$arr = array
(
'Name'=>'希亞',
'Age'=>20
);
$jsonencode = json_encode($arr);
echo $jsonencode;
?>
程序運行結果以下:
{"Name":null,"Age":20}
json_encode 函數中中文被編碼成 null 了,Google 了一下,很簡單,爲了與前端緊密結合,Json 只支持 utf-8 編碼,我認爲是前端的 Javascript 也是 utf-8 的緣由。
<?php
$array = array
(
'title'=>iconv('gb2312','utf-8','這裏是中文標題'),
'body'=>'abcd...'
);
echo json_encode($array);
?>
這個程序的運行結果爲:
{"title":"\u8fd9\u91cc\u662f\u4e2d\u6587\u6807\u9898","body":"abcd..."}json
-----{["標題1"]:["標題內容"],["標題2"]:["標題內容"],XXXXXX}函數
(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. 編碼
範例 spa
Example #1 json_decode() 的例子 .net
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?> code
output #1:htm
object(stdClass)#1 (5) { ip
["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)
}
Example #2 json_decode() 的例子
$data='[{"Name":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000","QQNo":""}]';
echo json_decode($data,true);
output#2:
Array ( [0] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) )
echo json_decode($data,true);
Array ( [0] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) )