Posted By

mscribellito on 05/11/11


Tagged


Versions (?)

PHP Array and Object Converter


 / Published in: PHP
 

  1. function objectToArray($object) {
  2.  
  3. if (!is_object($object)) return FALSE;
  4.  
  5. $array = array();
  6.  
  7. foreach (get_object_vars($object) as $key => $value) {
  8.  
  9. if ( ! is_object($value)) {
  10. $array[$key] = $value;
  11. } else {
  12. $array[$key] = is_array($value) ? $value : objectToArray($value);
  13. }
  14.  
  15. }
  16.  
  17. return $array;
  18.  
  19. }
  20.  
  21. function arrayToObject($array) {
  22.  
  23. if (!is_array($array)) return FALSE;
  24.  
  25. $object = new stdClass();
  26.  
  27. foreach ($array as $key => $value) {
  28.  
  29. if ( ! is_array($value)) {
  30. $object->$key = $value;
  31. } else {
  32. $object->$key = is_object($value) ? $value : arrayToObject($value);
  33. }
  34. }
  35.  
  36. return $object;
  37.  
  38. }

Report this snippet  

You need to login to post a comment.