Home > php教程 > php手册 > php对象和数组相互转换的方法

php对象和数组相互转换的方法

WBOY
Release: 2016-06-13 09:04:18
Original
1091 people have browsed it

php对象和数组相互转换的方法

   本文实例讲述了php对象和数组相互转换的方法。分享给大家供大家参考。具体分析如下:

  这里定义2个php匿名对象和数组相互转换的函数,代码如下:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

function array2object($array) {

if (is_array($array)) {

$obj = new StdClass();

foreach ($array as $key => $val){

$obj->$key = $val;

}

}

else { $obj = $array; }

return $obj;

}

function object2array($object) {

if (is_object($object)) {

foreach ($object as $key => $value) {

$array[$key] = $value;

}

}

else {

$array = $object;

}

return $array;

}

  用法示例如下:

  ?

1

2

3

4

5

$array = array('foo' => 'bar','one' => 'two','three' => 'four');

$obj = array2object($array);

print $obj->one; // output's "two"

$arr = object2array($obj);

print $arr['foo']; // output's bar

  希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template