php 对象如何变成数组

在PHP中,对象可以很方便地进行操作,但有时候需要将对象转换为数组或将对象的属性和方法以数组形式进行处理。本文将详细介绍如何将PHP对象转换为数组的方法。

一般来说,对象转换为数组的方法有两种:一种是使用对象的内置方法进行转换,另一种是通过自定义方法进行转换。

方法一:使用对象的内置方法

PHP提供了两个内置方法来将对象转换为数组:get_object_vars()和json_decode()。get_object_vars()函数返回一个包含所有可见属性的关联数组,json_decode()函数可以将JSON格式的字符串转换为数组或对象。

示例代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class Person {

public $name;

public $age;

public function __construct(string $name, int $age) {

$this->name = $name;

$this->age = $age;

}

}

$person = new Person(John, 25);

// 使用get_object_vars()方法

$person_array1 = get_object_vars($person);

print_r($person_array1);

// 使用json_decode()方法

$person_json = json_encode($person);    // 将对象转换为JSON字符串

$person_array2 = json_decode($person_json, true);

print_r($person_array2);

登录后复制

输出结果:

1

2

3

4

5

6

7

8

9

10

Array

(

[name] => John

[age] => 25

)

Array

(

[name] => John

[age] => 25

)

登录后复制

可以看到,两种方法都可以很方便地将对象转换为数组。

方法二:通过自定义方法进行转换

除了使用内置方法外,我们还可以通过自定义方法来将对象转换为数组。这种方法通常用于需要转换多个属性或需要对属性进行额外处理的情况。

示例代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

class Person {

public $name;

public $age;

public function __construct(string $name, int $age) {

$this->name = $name;

$this->age = $age;

}

public function toArray() {

return [

name => strtoupper($this->name),

age => $this->age,

];

}

}

$person = new Person(John, 25);

// 使用自定义方法

$person_array = $person->toArray();

print_r($person_array);

登录后复制

输出结果:

1

2

3

4

5

Array

(

[name] => JOHN

[age] => 25

)

登录后复制

可以看到,通过自定义方法可以很方便地将对象转换为数组,并对属性进行额外处理。

总结

本文介绍了两种将PHP对象转换为数组的方法。对于简单的对象,使用内置方法即可;对于需要额外处理的情况,可以通过自定义方法来实现。无论是哪种方法,都十分方便实用,可以轻松将对象转换为数组,以便于进行进一步的操作。

以上就是php 对象如何变成数组的详细内容,更多请关注php中文网其它相关文章!

TG交流群(点击进入)----付费帮助搭建---修复---二开,以及发布求资源.
QQ交流群 922260178
© 版权声明
THE END
喜欢就支持一下吧
点赞1.8W+ 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容