插件窝 干货文章 php中object怎么转数组

php中object怎么转数组

object array 对象 数组 653    来源:    2025-03-16

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

1. 使用 (array) 强制类型转换

你可以使用 (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. 使用 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_encodejson_decode 是一个不错的选择。

根据你的具体需求选择合适的方法。