The purpose of multi-layer array and object conversion is very simple, which is convenient for processing multi-layer array and object conversion in WebService
Simple (array) and (object) can only handle single-level data, and are powerless for multi-level array and object conversion.
The object can be converted into an array at one time through json_decode(json_encode($object), but there will be problems when encountering non-utf-8 encoded non-ascii characters in the object, such as gbk Chinese, not to mention the performance of json_encode and decode It is also worth doubting
The code below:
Copy the codeThe code is as follows:
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 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);
?>
http://www.bkjia.com/PHPjc/328084.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328084.htmlTechArticleThe purpose of multi-layer array and object conversion is very simple, which is convenient for processing the conversion of multi-layer arrays and objects in WebService Simple (array) and (object) can only handle single-level data. For multi-level arrays...