在PHP中,你可以使用几种方法将对象(object)转换为数组(array)。以下是几种常见的方法:
(array)
类型转换你可以直接将对象强制转换为数组:
$object = new stdClass();
$object->name = "John";
$object->age = 30;
$array = (array) $object;
print_r($array);
输出:
Array
(
[name] => John
[age] => 30
)
json_decode
和 json_encode
你可以先将对象转换为JSON字符串,然后再将JSON字符串解码为数组:
$object = new stdClass();
$object->name = "John";
$object->age = 30;
$json = json_encode($object);
$array = json_decode($json, true);
print_r($array);
输出:
Array
(
[name] => John
[age] => 30
)
get_object_vars
函数get_object_vars
函数可以获取对象的属性并返回一个关联数组:
$object = new stdClass();
$object->name = "John";
$object->age = 30;
$array = get_object_vars($object);
print_r($array);
输出:
Array
(
[name] => John
[age] => 30
)
Reflection
类如果你需要更复杂的转换,可以使用 Reflection
类来获取对象的属性和方法:
$object = new stdClass();
$object->name = "John";
$object->age = 30;
$reflection = new ReflectionObject($object);
$properties = $reflection->getProperties();
$array = [];
foreach ($properties as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
}
print_r($array);
输出:
Array
(
[name] => John
[age] => 30
)
(array)
类型转换或 get_object_vars
函数。json_decode
和 json_encode
或 Reflection
类。根据你的需求选择合适的方法。如果你只需要简单的属性转换,(array)
或 get_object_vars
是最直接和高效的方式。