Server-Side Magazine

How to Convert Array Notation to Object Notation

So do you want to convert an array to an object for no particular reason?

I worked on a project where I wrote this code. The class below eats up to 2536 bytes of memory, but make sure to read this whole post for the surprise!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class array_to_object
{
    function __construct($data=null, &$node=null)
    {
        foreach ( $data as $key => $value )
        {
            if ( is_array($value) )
            {
                if (! $node )
                {
                    $node =& $this;
                }
 
                $node->$key = new stdClass();
                self::__construct($value,$node->$key);
            }
            else
            {
                if (! $node )
                {
                    $node =& $this;
                }
 
                $node->$key = $value;
            }
        }
    }
}

The code above creates a new stdClass, PHP’s built-in class and uses it to create properties out of the array’s keys inside the object.

Basically, this $arr['hello'] = ‘world!’; becomes this $arr->hello = ‘world!’;

Now, here comes the surprise!

Hardcore one liner

1
2
3
4
function array2obj($data) 
{
    return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}

The function above does the same thing, except it uses 72 bytes of memory and it’s much more optimized!

Related Posts

Tags: , ,

About the Author

Server-Side Magazine

Server-Side Magazine is a place where users can contribute articles. Strictly server-side posts are presented in the following programming languages: PHP, Ruby, ASP.Net, Java, Python

Our philosophy is that knowledge should be free and available to anyone. We designed this site to be an open platform, meaning that anyone can contribute and share their knowledge on the above areas.

Although, it's an open platform we don't accept all articles, because it would result in a "just another", mediocre website. A minimum standard of quality is required from every submitted article.

Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Markdown enabled. Click here to see the syntax.

 
More in PHP (1 of 9 articles)