Posted By

realpeterz on 04/09/11


Tagged

php object array


Versions (?)

PHP - Convert Array to Object with stdClass


 / Published in: PHP
 

URL: http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass

  1. <?php
  2. $person = array (
  3. 'firstname' => 'Richard',
  4. 'lastname' => 'Castera'
  5. );
  6.  
  7. $p = (object) $person;
  8. echo $p->firstname; // Will print 'Richard'
  9. ?>
  10.  
  11. <?php
  12. function arrayToObject($array) {
  13. if(!is_array($array)) {
  14. return $array;
  15. }
  16.  
  17. $object = new stdClass();
  18. if (is_array($array) && count($array) > 0) {
  19. foreach ($array as $name=>$value) {
  20. $name = strtolower(trim($name));
  21. if (!empty($name)) {
  22. $object->$name = arrayToObject($value);
  23. }
  24. }
  25. return $object;
  26. }
  27. else {
  28. return FALSE;
  29. }
  30. }
  31. ?>
  32.  
  33. <?php
  34. $person = array (
  35. 'first' => array('name' => 'Richard')
  36. );
  37.  
  38. $p = arrayToObject($person);
  39. ?>
  40.  
  41. <?php
  42. // Now you can use $p like this:
  43. echo $p->first->name; // Will print 'Richard'
  44. ?>

Report this snippet  

You need to login to post a comment.