How can I convert an array like this to an object?
[128] => Array
(
[status] => "Figure A.
Facebook\'s horizontal scrollbars showing u
Its way to simple, This will create an object for recursive arrays as well:
$object = json_decode(json_encode((object) $yourArray), FALSE);
recursion is your friend:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
In the simplest case, it's probably sufficient to "cast" the array as an object:
$object = (object) $array;
Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
As Edson Medina pointed out, a really clean solution is to use the built-in json_
functions:
$object = json_decode(json_encode($array), FALSE);
This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.
Warning! (thanks to Ultra for the comment):
json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL
one liner
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
CakePHP has a recursive Set::map class that basically maps an array into an object. You may need to change what the array looks like in order to make the object look the way you want it.
http://api.cakephp.org/view_source/set/#line-158
Worst case, you may be able to get a few ideas from this function.
There's no built-in method to do it as far as I'm aware, but it's as easy as a simple loop:
$obj= new stdClass();
foreach ($array as $k=> $v) {
$obj->{$k} = $v;
}
You can expound on that if you need it to build your object recursively.