How can i convert an array like this to 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 ) )
How can i convert an array like this to 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 ) )
Depending on where you need that and how to access the object there are different ways to do it.
For example: just typecast it
However, the most compatible one is using a utility method (not yet part of PHP) that implements standard PHP casting based on a string that specifies the type (or by ignoring it just de-referencing the value):
The usage example in your case (Online Demo):
The easy way would be
But that's not what you want. If you want objects you want to achieve something, but that's missing in this question. Using objects just for the reason of using objects makes no sense.
The one I use (it is a class member):
This requires PHP7 because I chose to use a lambda function to lock away the 'innerfunc' within the main function. The lambda function is called recursively, hence the need for: "use ( &$innerfunc )". You could do it in PHP5 but could not hide the innerfunc.
Obviously just an extrapolation of some other folks' answers, but here's the recursive function that will convert any mulch-dimensional array into an object:
And remember that if the array had numeric keys they can still be referenced in the resulting object by using
{}
(for instance:$obj->prop->{4}->prop
)Using
json_encode
is problematic because of the way that it handles non UTF-8 data. It's worth noting that thejson_encode
/json_encode
method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without usingjson_
functions. Here's what I came up with: