在PHP中,将对象(object
)转换为数组(array
)有多种方法。以下是几种常见的方式:
(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
)
ReflectionClass
(适用于复杂对象)如果你需要处理更复杂的对象(例如包含私有或受保护的属性),可以使用 ReflectionClass
。
class Person {
public $name = 'John';
private $age = 30;
}
$object = new Person();
$reflection = new ReflectionClass($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
是最简单的方法。ReflectionClass
。json_encode
和 json_decode
是一个不错的选择。根据你的具体需求选择合适的方法。