在PHP中,你可以使用多种方法将对象转换为数组。以下是几种常见的方法:
(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
)
ArrayObject
如果你希望对象本身可以像数组一样操作,可以使用 ArrayObject
类。
$object = new ArrayObject([
'name' => 'John',
'age' => 30
]);
$array = $object->getArrayCopy();
print_r($array);
输出:
Array
(
[name] => John
[age] => 30
)
(array)
或 get_object_vars
是最直接的方法。json_decode
和 json_encode
是一个不错的选择。ReflectionClass
。根据你的需求选择合适的方法即可。