PHP - Convert Array to Object with stdClass


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.