php对象转数组的函数

关于php中想让对象以数组的形式访问,这时候就需要使用到get_object_vars()函数了。先来介绍一下这个函数。

官方文档是这样解释的:

1

array get_object_vars ( object $obj )

返回由 obj 指定的对象中定义的属性组成的关联数组。

举例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?php

class Point2D {

  var $x, $y;

  var $label;

  function Point2D($x, $y)

  {

    $this->x = $x;

    $this->y = $y;

  }

  function setLabel($label)

  {

    $this->label = $label;

  }

  function getPoint()

  {

    return array("x" => $this->x,

           "y" => $this->y,

           "label" => $this->label);

  }

}

// "$label" is declared but not defined

$p1 = new Point2D(1.233, 3.445);

print_r(get_object_vars($p1));

$p1->setLabel("point #1");

print_r(get_object_vars($p1));

?>

输出:

1

2

3

4

5

6

7

8

9

10

11

12

Array

 (

     [x] => 1.233

     [y] => 3.445

     [label] =>

 )

 Array

 (

     [x] => 1.233

     [y] => 3.445

     [label] => point #1

 )

对象转数组具体实现:

1

2

3

4

5

6

7

8

9

10

function objectToArray($obj) {

  //首先判断是否是对象

  $arr = is_object($obj) ? get_object_vars($obj) : $obj;

  if(is_array($arr)) {

    //这里相当于递归了一下,如果子元素还是对象的话继续向下转换

    return array_map(__FUNCTION__, $arr);

  }else {

    return $arr;

  }

}

数组转对象的具体实现:

1

2

3

4

5

6

7

function arrayToObject($arr) {

  if(is_array($arr)) {

    return (object)array_map(__FUNCTION__, $arr);

  }else {

    return $arr;

  }

}

「大理石平台维修」大理石平台如何进行维修可以使用更长时间?

原文地址:https://www.cnblogs.com/furuihua/p/11468223.html