插件窝 干货文章 php怎么把object转化成数组

php怎么把object转化成数组

object array 转换 使用 970    来源:    2025-03-18

在PHP中,你可以使用几种方法将对象(object)转换为数组(array)。以下是几种常见的方法:

1. 使用 (array) 类型转换

你可以直接将对象强制转换为数组:

$object = new stdClass();
$object->name = "John";
$object->age = 30;

$array = (array) $object;

print_r($array);

输出:

Array
(
    [name] => John
    [age] => 30
)

2. 使用 json_decodejson_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
)

3. 使用 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
)

4. 使用 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_decodejson_encodeReflection 类。

根据你的需求选择合适的方法。如果你只需要简单的属性转换,(array)get_object_vars 是最直接和高效的方式。