在處理 API 回傳、設定檔解析或資料庫 ORM 時,常需在 stdClass 物件與關聯陣列之間轉換。PHP 沒有內建單一函式完美處理巢狀結構,以下提供兩個簡易函式。
function array2object($array) {
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val) {
$obj->$key = $val;
}
return $obj;
}
return $array; // 非陣列直接回傳
}
function object2array($object) {
if (is_object($object)) {
$array = array();
foreach ($object as $key => $value) {
$array[$key] = $value;
}
return $array;
}
return $object; // 非物件直接回傳
}
$array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four');
$obj = array2object($array);
print $obj->one; // 輸出 "two"
$arr = object2array($obj);
print $arr['foo']; // 輸出 "bar"
json_decode(json_encode($data), true) 快速深度轉換,但效能稍差且會丟失私有屬性。