Home >Backend Development >PHP Tutorial >How to use recursion to convert between PHP arrays and objects_PHP Tutorial

How to use recursion to convert between PHP arrays and objects_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 09:48:46901browse

How to use recursion to achieve conversion between PHP arrays and objects

This article describes the example of using recursion to achieve conversion between PHP arrays and objects. Share it with everyone for your reference. The specific implementation method is as follows:

This involves some simple conversion issues between objects and arrays. Two methods are written recursively as follows:

 ?

 1

 2

 3

 4

 5

 6

7

 8function arrayToObject($e){

 if( gettype($e)!='array' ) return;

foreach($e as $k=>$v){

 if( gettype($v)=='array' || getType($v)=='object' )

 $e[$k]=(object)arrayToObject($v);

 }

return (object)$e;

 }

 ?

 1

 2

 3

 4

 5

 6

7

 8

 9function objectToArray($e){

 $e=(array)$e;

foreach($e as $k=>$v){

 if( gettype($v)=='resource' ) return;

 if( gettype($v)=='object' || gettype($v)=='array' )

 $e[$k]=(array)objectToArray($v);

 }

return $e;

 }

 ?

 1

 2

 3

 4

 5

 6

7

 8function object_to_array($e) {

 $_arr = is_object($e) ? get_object_vars($e) : $e;

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

 $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;

$arr[$key] = $val;

 }

return $arr;

 }

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1020893.htmlTechArticleHow to use recursion to achieve conversion between PHP arrays and objects. This article describes the use of recursion between PHP arrays and objects. Method to implement conversion. Share it with everyone for your reference. Specific implementation...
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