I’m really surprised that PHP 5 does not have built-in functionality for converting objects into arrays. Basically I had an Ajax function sending me a javascript object in JSON format to my PHP method. My method was already setup to handle an array, so after decoding the JSON into a PHP object and passed the object into this function.
1 2 3 4 5 6 7 8 9 | function objectToArray($object) { $array=array(); foreach($object as $member=>$data) { $array[$member]=$data; } return $array; } |
The problem with this method is that it will only move public variables into the array. Anything that is private cannot be accessed. You can try type casting your PHP 5 object to an array.
$array = (array) $this;
When I did this I got some really strange characters in the array. It does not seem that there is an easy way to convert a PHP 5 object to an array. Your best bet is to write a custom function that either converts your objects variables into array elements or if you are connecting to a database, just return the result set that builds the object in array form.
Related posts:
You might want to go ahead and check out the get_object_vars() function. Just enter an object instance as your parameter, and your result is an array of the properties in that object. Very nice and built in method to accomplish what your function does.
I will absolutely check this out. Will this work on private object members as well?
Dude Good example but use proper naming conventions for variables . You are spoiling my programmers
Dude, did you forget about get_object_vars method (built in) of PHP?
What are you talking about? There are no naming conventions in PHP…
enhance version
function objectToArray($object)
{
if(!is_object($object) && !is_array($object))
return $object;
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=objectToArray($data);
}
return $array;
}
Hi All, I may have got the wrong end of the stick here but I see the only way to grab properties of any visibility from an object would be inside the object itself, hence…
class MyObject
{
public $test = ‘test’;
protected $test2 = ‘test2′;
private $test3 = ‘test3′;
public function iterate(&$arr) {
foreach($this as $key => $value) {
$arr[$key] = $value;
}
}
}
$obj = new MyObject();
$myArray = array();
$obj->iterate($myArray);
print_r($myArray);
There are several ways to convert objects into an array using php, in fact the object itself can be used as an array as you described in your orignial post. Did you get a chance to have a look at the SPL ArrayObject class or any of the iterator interfaces included as standard in php? These might what you are looking for.
If i understand this correctly you are converting a JSON object to and PHP Object then converting it to an Array.
If so you can actually set the “assoc” Parameter to to true to convert JSON object directly to PHP Array. It works very well.
eg.
$phpArray = json_decode ( $jsonObj, true);