要將數組轉換為對象,請使用 stdClass()。 stdClass() 是一個空類,用於將其他類型轉換為對象。如果將對象轉換為對象,則不會對其進行修改。但是,如果對象類型被轉換/type-casted,則會創建 stdClass 的實例,如果它不是 NULL。如果為 NULL,則新實例將為空。
範例1:它使用 stdClass 將數組轉換為對象。
PHP
<?php
// Function to convert array into
// stdClass object
function ToObject($Array) {
// Create new stdClass object
$object = new stdClass();
// Use loop to convert array into
// stdClass object
foreach ($Array as $key => $value) {
if (is_array($value)) {
$value = ToObject($value);
}
$object->$key = $value;
}
return $object;
}
// Declare an array and initialize it
$Original = array (
'1' => array(
'sNo' => '1',
'Age' => '20',
'name' => 'A'
),
'2' => array(
'sNo' => '2',
'Age' => '21',
'name' => 'B'
),
'3' => array(
'sNo' => '3',
'Age' => '22',
'name' => 'C'
),
'4' => array(
'sNo' => '4',
'Age' => '23',
'name' => 'D'
),
'5' => array(
'sNo' => '5',
'Age' => '24',
'name' => 'E'
)
);
// Display the original array
print_r($Original);
// Function call
$convertedObj = ToObject($Original);
// Display the stdClass object
print_r($convertedObj);
?>
輸出:
Array ( [1] => Array ( [sNo] => 1 [Age] => 20 [name] => A ) [2] => Array ( [sNo] => 2 [Age] => 21 [name] => B ) [3] => Array ( [sNo] => 3 [Age] => 22 [name] => C ) [4] => Array ( [sNo] => 4 [Age] => 23 [name] => D ) [5] => Array ( [sNo] => 5 [Age] => 24 [name] => E ) ) stdClass Object ( [1] => stdClass Object ( [sNo] => 1 [Age] => 20 [name] => A ) [2] => stdClass Object ( [sNo] => 2 [Age] => 21 [name] => B ) [3] => stdClass Object ( [sNo] => 3 [Age] => 22 [name] => C ) [4] => stdClass Object ( [sNo] => 4 [Age] => 23 [name] => D ) [5] => stdClass Object ( [sNo] => 5 [Age] => 24 [name] => E ) )
範例2:它使用 stdClass 將數組轉換為對象。
PHP
<?php
// Function to convert array into
// stdClass object
function ToObject($Array) {
// Create new stdClass object
$object = new stdClass();
// Use loop to convert array into object
foreach ($Array as $key => $value) {
if (is_array($value)) {
$value = ToObject($value);
}
$object->$key = $value;
}
return $object;
}
// Declare an array
$Original = array(1, 2, 3, 4, 5, 6);
// Display the array element
print_r($Original);
// Function call to convert object
$convertedObj = ToObject($Original);
// Display the stdClass object
print_r($convertedObj);
?>
輸出:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) stdClass Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
相關用法
- PHP Date轉Timestamp用法及代碼示例
- PHP Integer轉String用法及代碼示例
- PHP string轉number用法及代碼示例
- Javascript object轉string用法及代碼示例
- Javascript Array轉Object用法及代碼示例
注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 How to convert an array into object using stdClass() in PHP?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。