温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用php将对象转化为数组

发布时间:2023-03-28 09:46:53 来源:亿速云 阅读:97 作者:iii 栏目:编程语言

这篇文章主要介绍了如何用php将对象转化为数组的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇如何用php将对象转化为数组文章都会有所收获,下面我们一起来看看吧。

1.使用get_object_vars()函数

PHP提供了get_object_vars()函数,它可以将对象的属性值转化为一个关联数组。这个函数接收一个对象作为参数,并返回一个数组,数组的键是对象属性的名称,数组的值是属性的值。下面是一个例子:

class Person {
    public $name;
    public $age;
    public $gender;
    public function __construct($name, $age, $gender) {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
}
$person = new Person('Tom', 18, 'male');
$arr = get_object_vars($person);
print_r($arr);

输出结果为:

Array
(
    [name] => Tom
    [age] => 18
    [gender] => male
)

2.使用json_encode()函数

除了使用get_object_vars()函数之外,我们还可以使用json_encode()函数将对象转换为JSON格式的字符串,然后使用json_decode()函数将其转换为数组。下面是一个例子:

class Person {
    public $name;
    public $age;
    public $gender;
    public function __construct($name, $age, $gender) {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
}
$person = new Person('Tom', 18, 'male');
$jsonStr = json_encode($person);
$arr = json_decode($jsonStr, true);
print_r($arr);

输出结果和上一个例子相同。

3.使用对象的__toArray()方法

如果你掌握了面向对象编程的基础知识,那么你可以在自己的类中定义一个__toArray()方法,该方法用于将对象的属性值转化为一个数组。下面是一个例子:

class Person {
    public $name;
    public $age;
    public $gender;
    public function __construct($name, $age, $gender) {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
    public function __toArray() {
        $arr = [];
        $arr['name'] = $this->name;
        $arr['age'] = $this->age;
        $arr['gender'] = $this->gender;
        return $arr;
    }
}
$person = new Person('Tom', 18, 'male');
$arr = $person->__toArray();
print_r($arr);

输出结果也和前面两个例子相同。

关于“如何用php将对象转化为数组”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“如何用php将对象转化为数组”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI