PHP 中關於陣列與 JSON 的轉換
4,262 0
這段時間在開發一個短網址的 API 介面,就看了很多關於 API 的相關文章,最常用到的就是 JSON 技術,JSON 又叫做 JS 物件標記,是一種輕量級的資料交換格式,因為我的 API 開發語言是 PHP,所以在資料處理的過程中,就要用到 JSON 與 PHP 的互動,也就是資料轉換。

下面我主要介紹一下 JSON 與陣列(Array)的轉換的兩種方式。
json_encode()
由於 JSON 只接受 UTF-8 編碼的字元,所以 json_encode() 的參數必須是 UTF-8 編碼,否則會得到空字元或者 null,當中文使用 GB2312 編碼的時候,這一點要特別注意!
實例一(陣列)
PHP PHP
<?php
$array_a =array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($array_a);
?>
輸出
JSON JSON
{"a":1,"b":2,"c":3,"d":4,"e":5}
實例二(物件)
PHP PHP
<?php
$obj->body = 'another post';
$obj->id = 21;
$obj->approved = true;
$obj->favorite_count = 1;
$obj->status = NULL;
echo json_encode($obj);
?>
輸出
JSON JSON
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
json_decode()
該函式用於將 JSON 文字轉換為相應的 PHP 資料結構,通常情況下,json_decode() 總是返回一個 PHP 物件而不是陣列。
案例三
PHP PHP
<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
輸出
PHP PHP
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
如果想要強制生成 PHP 關聯陣列,json_decode() 需要加一個參數 true。
實例四
PHP PHP
<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?>
輸出
PHP PHP
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
另外,JSON 只能用來表示物件(object)和陣列(array),如果對字串或數值使用 json_decode() 將會返回 null 。
評論
(0)暫無評論,來說兩句吧