php simple object and array conversion function code of php multilayer array and object conversion

  • 2020-05-07 19:18:50
  • OfStack

 
function 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; 
} 

function 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; 
} 

The above is from cnblogs jaiho
php multilayer array and object conversion
The purpose of multilayer arrays and object conversions is simple and easy to handle in WebService
The simple (array) and (object) can handle only one layer of data, but not multilayer arrays and object transformations.
json_decode(json_encode($object) can be used to convert an object to an array once, but object has problems with non-utf-8 encoding of non-ascii characters, such as gbk's Chinese, and the performance of json_encode and decode is questionable.

The above code is as follows:
 
<?php 

function objectToArray($d) { 
if (is_object($d)) { 
// Gets the properties of the given object 
// with get_object_vars function 
$d = get_object_vars($d); 
} 

if (is_array($d)) { 
/* 
* Return array converted to object 
* Using __FUNCTION__ (Magic constant) 
* for recursive call 
*/ 
return array_map(__FUNCTION__, $d); 
} 
else { 
// Return array 
return $d; 
} 
} 

function arrayToObject($d) { 
if (is_array($d)) { 
/* 
* Return array converted to object 
* Using __FUNCTION__ (Magic constant) 
* for recursive call 
*/ 
return (object) array_map(__FUNCTION__, $d); 
} 
else { 
// Return object 
return $d; 
} 
} 

// Useage: 
// Create new stdClass Object 
$init = new stdClass; 
// Add some test data 
$init->foo = "Test data"; 
$init->bar = new stdClass; 
$init->bar->baaz = "Testing"; 
$init->bar->fooz = new stdClass; 
$init->bar->fooz->baz = "Testing again"; 
$init->foox = "Just test"; 

// Convert array to object and then object back to array 
$array = objectToArray($init); 
$object = arrayToObject($array); 

// Print objects and array 
print_r($init); 
echo "\n"; 
print_r($array); 
echo "\n"; 
print_r($object); 
?> 


Related articles: