Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php对象数组转数组

作者:颓废的爱情   发布日期:2024-03-17   浏览:1010

在PHP中,可以使用get_object_vars()函数将对象转换为数组。然后,可以使用循环遍历数组中的每个对象,并使用get_object_vars()函数将其转换为关联数组。

以下是一个示例代码:

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person1 = new Person("John", 25);
$person2 = new Person("Jane", 30);

$persons = array($person1, $person2);

$personsArray = array();

foreach ($persons as $person) {
    $personsArray[] = get_object_vars($person);
}

print_r($personsArray);

输出结果为:

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 25
        )

    [1] => Array
        (
            [name] => Jane
            [age] => 30
        )

)

在上面的示例中,创建了一个Person类,并实例化了两个Person对象。然后,将这两个对象放入一个数组中。接下来,通过循环遍历数组中的每个对象,并使用get_object_vars()函数将其转换为关联数组。最后,使用print_r()函数打印转换后的数组。

上一篇:php 怎么定义二维数组

下一篇:php 数组 是否包含

大家都在看

php session用法

php 定义常量

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站