DevelopmentNow Blog
 Saturday, September 19, 2009

We recently needed to convert a complex array structure to an object-based one in PHP. We started off with Marcel's array2object function but realized that we only wanted to "objectify" associative arrays, and leave non-associative arrays to as arrays. So here's the final function, using vhermecz's function to detect associative arrays:


function array2object($data) {
   if (!is_array($data)) return $data;
   $is_assoc = is_assoc($data);

   $object = new stdClass();

   if (count($data) == 0) return $data;

   if (is_array($data) && count($data) > 0) {
      foreach ($data as $name=>$value) {
         if ($name !== '') {
            $object->$name = array2object($value);
            $data[$name] = array2object($value);
         }
      }

   }
   if ($is_assoc)
        return $object;
   else
        return $data;
}


function is_assoc($var) {
    return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}

PHP
September 19, 2009    Bookmark to Digg or other social bookmarking
#    Disclaimer  |  Comments [0]



 Tuesday, February 17, 2009

After spending a ton of time in Ruby on Rails we're getting back into some more PHP projects. And ASP.NET. :) Granted, it would be nice to only stick with one language, but a lot of our projects tend to involve solutions and packages instead of a lot of ground-up coding.

Anyhow, this is mainly a link for me to check out later if we need it: Tyler Hall's Simple PHP Framework.

http://code.google.com/p/simple-php-framework/wiki/ExampleWebsites

http://groups.google.com/group/simple-php-framework

 

 

February 17, 2009    Bookmark to Digg or other social bookmarking
#    Disclaimer  |  Comments [0]