In some cases, especially while working with API or web service response. It often returns an object rather a string; therefore, you can not parse the result without converting.
In this tutorial, I’ll give you a simple function and example on how to:
- 1. Convert stdClass Object to Array
- 2. Convert Array to stdClass Object
1. PHP Function Convert stdClass Object to Array
<?php function object2Array($d) { if (is_object($d)) { $d = get_object_vars($d); } if (is_array($d)) { return array_map(__FUNCTION__, $d); } else { return $d; } } ?> |
2. PHP Function Convert Array to stdClass Object
<?php function array2Object($d) { if (is_array($d)) { return (object) array_map(__FUNCTION__, $d); } else { return $d; } } ?> |
3. Usage the object2Array and array2Object function
<?php $std = new stdClass; $std->a = "This is value for a"; $std->b = "This is value for b"; $std->c->c_std = new stdClass; $std->c->c_std->c1 = "This is value for c1 in c_std stdClass"; $std->c->c_std->c2 = "This is value for c2 in c_std stdClass"; $std->d = "This is value for d"; print_r($std); echo "\r\n"; $array = object2Array($std); print_r($array); echo "\r\n"; $object = array2Object($array); print_r($object); echo "\r\n"; ?> |
The output:
stdClass Object ( [a] => This is value for a [b] => This is value for b [c][/c] => stdClass Object ( [c_std] => stdClass Object ( [c1] => This is value for c1 in c_std stdClass [c2] => This is value for c2 in c_std stdClass ) ) [d] => This is value for d ) Array ( [a] => This is value for a [b] => This is value for b [c][/c] => Array ( [c_std] => Array ( [c1] => This is value for c1 in c_std stdClass [c2] => This is value for c2 in c_std stdClass ) ) [d] => This is value for d ) stdClass Object ( [a] => This is value for a [b] => This is value for b [c][/c] => stdClass Object ( [c_std] => stdClass Object ( [c1] => This is value for c1 in c_std stdClass [c2] => This is value for c2 in c_std stdClass ) ) [d] => This is value for d ) |
Download the source code & example above.