PHP Object to Array
From w3cyberlearnings
Contents |
PHP Object To Array
Convert simple Object to array is easy, however to convert a complex Object is tricky. You need to write a custom function to do the convertion recursively from Object to array. Please check the example on how to do it.
Example 1: Convert a simple object to an array
<?php $object = new stdClass(); $object->name = "Bob Markina"; $object->age = 24; $my_array = (array) $object; print_r($my_array); ?>
Output
Array ( [name] => Bob Markina [age] => 24 )
PHP Function to convert object to an array recursively
For complex object, you need to use this function to convert object to an array recursively.
<?php function objectToArray($d) { if (is_object($d)) { // Gets the properties of the object $d = get_object_vars($d); } if (is_array($d)) { return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } ?>
Example 2
Without using the custom function, you will not convert all objects to array correctly.
<?php require_once 'myfunction.php'; $employee_obj = new stdClass(); $employee_obj->name = 'Jamy Jo'; $employee_obj->age = 58; $employee_obj->address->street = '240 Lake Rd'; $employee_obj->address->apartment = '240'; $employee_obj->address->state = 'Tx'; $employee_obj->address->city = 'Houston'; $employee_obj->address->zip = '77300'; $employee_obj->role = 'PHP Developer'; // convert to an array use custom function $my_array = objectToArray($employee_obj); print_r($my_array); ?>
Output
Array ( [name] => Jamy Jo [age] => 58 [address] => Array ( [street] => 240 Lake Rd [apartment] => 240 [state] => Tx [city] => Houston [zip] => 77300 ) [role] => PHP Developer )
Related Links
--PHP Object to Array-- PHP Object to JSON-- PHP Access Object--