Home > Backend Development > PHP Tutorial > Methods to convert php objects and arrays to each other_PHP tutorial

Methods to convert php objects and arrays to each other_PHP tutorial

WBOY
Release: 2016-07-13 09:53:40
Original
996 people have browsed it

How to convert PHP objects and arrays to each other

This article describes the method of converting PHP objects and arrays to each other. Share it with everyone for your reference. The specific analysis is as follows:

Here are two functions for converting php anonymous objects and arrays. The code is as follows:

 ?

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

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

4

5

6

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; }
Usage examples are as follows:  ?
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
I hope this article will be helpful to everyone’s PHP programming design. http://www.bkjia.com/PHPjc/1000105.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1000105.htmlTechArticleHow to convert PHP objects and arrays to each other. This article explains how to convert PHP objects and arrays to each other. Share it with everyone for your reference. The specific analysis is as follows: 2 php anonymous are defined here...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template