php數組轉對象的方法:使用stdclass類使用json_decode()函數使用第三方庫(如arrayobject類、hydrator庫)
PHP 數組轉對象的常見方式
在 PHP 中,將數組轉換為對象有幾種方法。以下是一些常見的方法:
1. 使用 stdClass 類
stdClass 類是 PHP 提供的標準類,可以用來創建一個空對象。我們可以使用 stdClass 對象的屬性來存儲數組中的鍵值對。
$array = ['name' => 'John Doe', 'age' => 30];
$object = new stdClass();
foreach ($array as $key => $value) {
$object->$key = $value;
}
登錄后復制
2. 使用內置函數 json_decode()
json_decode() 函數可以將 JSON 字符串解碼為 PHP 對象。我們可以將數組轉換為 JSON 字符串,然后使用 json_decode() 函數將其解碼為對象。
$array = ['name' => 'John Doe', 'age' => 30]; $json = json_encode($array); $object = json_decode($json);
登錄后復制
3. 使用第三方庫
有一些第三方庫也可以用于數組和對象的轉換,例如:
ArrayObject 類([PHP 文檔](https://www.php.net/manual/en/class.arrayobject.php))Hydrator 庫([Composer](https://packagist.org/packages/laminas/laminas-hydrator))
實戰案例
假設我們有一個包含用戶數據的數組:
$users = [
['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Jane Doe', 'email' => '[email protected]'],
];
登錄后復制
我們可以使用上述方法將數組轉換為對象:
使用 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);
}
登錄后復制
現在,我們就有了包含用戶數據的對象集合,我們可以輕松地訪問它們的屬性。例如:
echo $object->name; // 輸出:"John Doe"
登錄后復制






