首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 物件轉陣列、JSON 轉陣列:核心函數與最佳實踐

     編輯:PHP 相關知識

PHP 物件轉陣列、JSON 轉陣列:核心函數與最佳實踐

開發中頻繁遇到 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 字串轉陣列:內建 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 回傳 nullJSON 格式錯誤(如尾隨逗號、單引號、BOM)用 json_last_error() 檢查;清洗輸入字串
大整數精度丟失PHP 整數範圍限制加 JSON_BIGINT_AS_STRING 選項或用字串存儲 ID
中文變 \uXXXXjson_encode 預設轉義 Unicode加 JSON_UNESCAPED_UNICODE 選項(PHP 5.4+)

延伸閱讀

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved