Jan 11

As you may already know, you can convert an array into an object simple like this:

 PHP |  copy code |? 
1
2
$array = array('first_name' => 'John', 'last_name' => 'Doe');
3
$object = (object) $array;
4

Then you call the object:

 PHP |  copy code |? 
1
2
echo $object->first_name;
3

The problem is that you can’t do this with multidimensional array. So, for this, i’ve found the solution:

 PHP |  copy code |? 
01
02
function arrayToObject($array)
03
{
04
    if(!is_array($array)) {
05
        return $array;
06
    }
07
 
08
    $object = new stdClass();
09
    if (is_array($array) && count($array) > 0) {
10
      foreach ($array as $name=>$value) {
11
         $name = strtolower(trim($name));
12
         if (!empty($name)) {
13
            $object->$name = arrayToObject($value);
14
         }
15
      }
16
      return $object;
17
    }
18
    else {
19
      return FALSE;
20
    }
21
}
22
 
23
// Now we can test the method
24
$array = array(
25
    'f_name' => 'Rada',
26
    'l_name' => 'Calin',
27
    'age' => 26,
28
    'parents' => array(
29
        'mom' => array(
30
            'f_name' => 'Rada',
31
            'l_name' => 'Daniela',
32
            'age' => 45,
33
        ),
34
        'dad' => array(
35
            'f_name' => 'Rada',
36
            'l_name' => 'Ioan',
37
            'age' => 46,
38
        )
39
    )
40
);
41
 
42
// Convert the array to object
43
$user = arrayToObject($array);
44
 
45
// Example output
46
echo $user->parents->mom->l_name;
47

Hope this is helpful ;)

written by calin \\ tags: , ,