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.



我可以说,我真的安定下来这样的编程技术 - 面向对象编程, PDO的数据库访问, JSON作为很好的客户端 - 服务器通信,超薄框架作为REST风格服务器, jQuery的骨干作为MV *客户端解决方案。

这是一个简短的说明有关数据库-PHP- JavaScript的通信。 PHP是从两个接收数据,但诀窍是 - 一,从JavaScript的未来是JSON字符串,另外一个,从数据库来为数组。 PHP有很好的功能转换JSON字符串到纯对象 -
 json_decode
但如何将数组对象?它应该是这么简单,对不对?但是,当它出现时,有单曲没有原生函数这样做。一种方法是将铸数组对象作为这样
$ NEWOBJECT = (对象) $阵列;
但...关键是,只有外形尺寸将被改造为一个对象。有definetely在互联网飞翔周围的一些递归函数,但..怎么样使用json_encode首先数组编码为JSON ,然后用json_decode解码呢?好吧,我承认这可能是更多的内存低效比一些递归函数,但是,它definetely是更简单。

Nav komentāru:

Komentāra publicēšana