How can I convert an array like this to an object?
[128] => Array ( [status] => "Figure A. Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution." ) [129] => Array ( [status] => "The other day at work, I had some spare time" )
Converting an object to an array with typecasting technique: php class bag { public function __construct( $item1, $item2, $item3){ $this->item1 = $item1; $this->item2 =$item2; $this->item3 = $item3; } } $myBag = new bag("Books", "Ball", "Pens"); echo "Before conversion :".
To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.
To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
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
you can simply use type casting to convert an array to object.
// *convert array to object* Array([id]=> 321313[username]=>shahbaz) $object = (object) $array_name; //now it is converted to object and you can access it. echo $object->username;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With