Home  >  Article  >  Backend Development  >  php对象和数组相互转换的方法_PHP教程

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

WBOY
WBOYOriginal
2016-07-13 09:53:40935browse

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程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1000105.htmlTechArticlephp对象和数组相互转换的方法 本文实例讲述了php对象和数组相互转换的方法。分享给大家供大家参考。具体分析如下: 这里定义2个php匿名...
Statement:
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