2014-01-23

Array to object in php

I could say that I`m settled down with such a programming techniques - object oriented programming, PDO for database access, JSON as nice client-server communication, Slim framework as RESTful server, jQuery-Backbone as MV* client side solution.

This is short note about database-php-javascript communication. PHP is receiving data from both, but the trick is - one, coming from javascript is JSON string, another one, coming from database is array. PHP has nice function converting JSON string to pure object -
 json_decode 
But how about converting array to object? It should be so simple, right? But as it appears, there`s no native functions for doing that. One way is to cast an array to object as such
$newObject =(object) $array;
but ... the trick is that only the outer dimension will be transformed to an object. There definetely are some recursive functions flyin around in internet, but .. how about firstly encoding array to JSON using json_encode, and then decoding it using json_decode? Ok, I admit it could be much more memory inefficient than some recursive function, but, it definetely is much more simple.