$associative$json = '{"a":1,"b":2}';
// 預設:回傳 stdClass 物件
$obj = json_decode($json);
var_dump($obj);
// object(stdClass)#1 (2) { ["a"]=>int(1) ["b"]=>int(2) }
echo $obj->a; // 1
// 設為 true:回傳關聯陣列
$arr = json_decode($json, true);
var_dump($arr);
// array(2) { ["a"]=>int(1) ["b"]=>int(2) }
echo $arr['a']; // 1
$json = '{"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}';
// 物件模式:巢狀也是物件
$obj = json_decode($json);
echo $obj->users[0]->name; // Alice
// 陣列模式:巢狀也是陣列
$arr = json_decode($json, true);
echo $arr['users'][0]['name']; // Alice
true(陣列模式)?| 優勢 | 說明 |
|---|---|
| 統一存取語法 | 陣列統一用 [],物件需用 ->,混用易出錯 |
| 序列化/儲存更安全 | serialize()/json_encode() 陣列行為穩定,物件可能帶入類別資訊 |
| 效能略優 | 陣列建立與存取在 Zend Engine 中較物件快 |
| 函數式操作友善 | array_map/filter/reduce 等原生陣列函數直接適用 |
| 避免動態屬性除錯困難 | 物件可隨意新增屬性,陣列結構固定易於靜態分析 |
| API 回應一致性 | 前端預期 JSON 物件,PHP 陣列 json_encode 後同樣輸出 JSON 物件 |
JsonSerializable 或自訂還原邏輯。function safeJsonDecode(string $json, bool $assoc = true): array|object|null {
try {
return json_decode($json, $assoc, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
} catch (JsonException $e) {
error_log("JSON decode failed: {$e->getMessage()}");
return null; // 或拋出自訂例外
}
}
$raw = file_get_contents('https://api.example.com/users');
$data = safeJsonDecode($raw, true);
if ($data === null) {
throw new RuntimeException('Invalid API response');
}
// 類型安全存取(PHP 8.1+ 型別檢查)
$userNames = array_column($data['users'] ?? [], 'name');
json_decode($json, true) 應為專案預設慣例。僅在極少數需保留物件行為時才使用預設模式。統一陣列模式能減少認知負擔、提升程式碼一致性、降低執行期錯誤風險。