當前位置: 首頁> 最新文章列表> PHP 數組轉對象的三種常見方式及應用實例

PHP 數組轉對象的三種常見方式及應用實例

M66 2025-09-24

PHP 數組轉對象的常見方式

在PHP 中,將數組轉換為對象的需求很常見,特別是在處理數據結構時。以下是幾種常見的轉換方式:

使用stdClass 類

stdClass 是PHP 提供的標準類,用來創建空對象。我們可以將數組中的鍵值對存儲為該對象的屬性。

 $array = [ 'name' => 'John Doe', 'age' => 30 ];
$object = new stdClass();
foreach ($array as $key => $value) {
    $object->$key = $value;
}

使用json_decode() 函數

json_decode() 函數能夠將JSON 字符串轉為PHP 對象。通過先將數組編碼為JSON 字符串,再使用該函數解碼為對象。

 $array = [ 'name' => 'John Doe', 'age' => 30 ];
$json = json_encode($array);
$object = json_decode($json);

使用第三方庫

除了內置的函數和類,PHP 還支持一些第三方庫來幫助我們實現數組和對象之間的轉換,例如:

  • ArrayObject 類
  • Hydrator 庫

實戰案例

假設我們有一個包含用戶數據的數組:

 $users = [
    [ 'id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com' ],
    [ 'id' => 2, 'name' => 'Jane Doe', 'email' => 'jane@example.com' ],
];

我們可以使用上述的任何方法來將數組轉換為對象。以下是三種常見方法的實戰演示:

使用stdClass 類:

 foreach ($users as $user) {
    $object = new stdClass();
    $object->id = $user['id'];
    $object->name = $user['name'];
    $object->email = $user['email'];
}

使用json_decode() 函數:

 foreach ($users as $user) {
    $json = json_encode($user);
    $object = json_decode($json);
}

使用ArrayObject 類:

 foreach ($users as $user) {
    $object = new ArrayObject($user);
}

通過上述方法,我們可以將用戶數據數組轉換為對象,從而在程序中更方便地操作這些數據。

以上就是PHP 數組轉對象的常見方式及應用示例。通過這些方法,你可以根據需求靈活地處理數據結構。