Posted By

MMDeveloper on 10/02/08


Tagged

class php object array convert


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

jamesming
purefusion


Convert Array to Object, infinite dimensions


 / Published in: PHP
 

This function will convert any multidimensional array to an equivalent multidimensional object. It will recursively traverse the array to an infinite number of dimensions.

  1. <?php
  2.  
  3. $array = array (
  4.  
  5. ),
  6.  
  7. )
  8. )
  9. );
  10.  
  11. function bindArrayToObject($array) {
  12. $return = new stdClass();
  13. foreach ($array as $k => $v) {
  14. if (is_array($v)) {
  15. $return->$k = bindArrayToObject($v);
  16. }
  17. else {
  18. $return->$k = $v;
  19. }
  20. }
  21.  
  22. return $return;
  23. }
  24.  
  25. $newObject = bindArrayToObject($array);
  26. print_r($newObject);
  27. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: purefusion on October 24, 2008

You may also be able to get away with doing: $obj = (object)$arr; Or as a specific class: $obj = (YourClass)$array;

Posted By: bugfix on October 21, 2011

Hello

Good work it is very useful.

However, maybe the is a gap that could be a problem : when we have an array in a standard object, this array will not be converted because the script will call itself only if the container is an array.

So we can fix it as this :

[...] foreach ($array as $k => $v) { if (isarray($v)) $return->$k = $this->bindArrayToObject($v); else if (isobject($v)) $return->$k = $this->bindArrayToObject($v); // BUG FIX else $return->$k = $v; } [...]

Now, we analyse the objects too, and if they contains arrays, they will be converted too.

if (isarray($v) || isobject($v)) is better but I want to if (is_array($v)) the line of the bugfix :)

Hope it's help.

Posted By: bugfix on October 21, 2011

I want to "highlight" the line, sorry of the bad paste !

You need to login to post a comment.