在PHP中,數組和對象之間可以相互轉換。以下是一些常用的方法:
$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$array = (array) $object;
print_r($array);
json_decode
函數將數組轉換為對象。$array = array('name' => 'John', 'age' => 30);
$object = (object) $array;
var_dump($object);
// 或者使用json_decode
$json = json_encode($array);
$object = json_decode($json);
var_dump($object);
get_object_vars
函數獲取對象的屬性并將其轉換為數組。$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$array = get_object_vars($object);
print_r($array);
json_encode
和json_decode
函數進行對象和數組之間的轉換。$object = new stdClass();
$object->name = 'John';
$object->age = 30;
// 將對象轉換為數組
$array = json_decode(json_encode($object), true);
print_r($array);
// 將數組轉換為對象
$object = json_decode(json_encode($array));
var_dump($object);