開發中頻繁遇到 stdClass 物件、JSON 字串與陣列互轉場景。本文整理兩大核心轉換方法,並提供遞迴處理多維結構的通用函數。
get_object_vars() 僅能處理單層公開屬性,遇到巢狀物件/陣列需遞迴處理:
/**
* 物件/陣列遞迴轉純陣列
* @param object|array $obj 輸入資料
* @return array
*/
function object_to_array($obj) {
$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($_arr as $key => $val) {
$val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}
使用範例:
$obj = json_decode('{"user":{"name":"Tom","tags":["php","js"]}}');
// $obj 為 stdClass 物件
$arr = object_to_array($obj);
// 結果:['user' => ['name' => 'Tom', 'tags' => ['php', 'js']]]
json_decode()PHP 5.2.0+ 內建支援,關鍵在於第二參數 $assoc = true:
$json = '{"id":1,"name":"John","roles":["admin","editor"]}';
// 預設回傳物件
$obj = json_decode($json);
// $obj->name === 'John'
// 設定 true 直接回傳關聯陣列
$arr = json_decode($json, true);
// $arr['name'] === 'John'
mixed json_decode(
string $json, // 待解碼 JSON 字串
bool $assoc = false, // true=回傳陣列, false=回傳物件
int $depth = 512, // 遞迴深度限制
int $options = 0 // 位元遮罩:JSON_BIGINT_AS_STRING 等
)
| 問題 | 原因 | 解決 |
|---|---|---|
| json_decode 回傳 null | JSON 格式錯誤(如尾隨逗號、單引號、BOM) | 用 json_last_error() 檢查;清洗輸入字串 |
| 大整數精度丟失 | PHP 整數範圍限制 | 加 JSON_BIGINT_AS_STRING 選項或用字串存儲 ID |
| 中文變 \uXXXX | json_encode 預設轉義 Unicode | 加 JSON_UNESCAPED_UNICODE 選項(PHP 5.4+) |