1$person = new stdClass();
2$person->firstName = "Taylor";
3$person->age = 32;
4
5//Convert Single-Dimention Object to array
6$personArray = (array) $person;
7
8//Convert Multi-Dimentional Object to Array
9$personArray = objectToArray($person);
10function objectToArray ($object) {
11 if(!is_object($object) && !is_array($object)){
12 return $object;
13 }
14 return array_map('objectToArray', (array) $object);
15}
1<?php
2class sample {
3
4 /* Member variables */
5 var $var1;
6 var $var2;
7
8 function __construct( $par1, $par2 )
9 {
10 $this->var1 = $par1;
11 $this->var2 = $par2;
12 }
13}
14
15// Creating the object
16$myObj = new sample(1000, "second");
17echo "Before conversion: \n";
18var_dump($myObj);
19
20// Converting object to associative array
21$myArray = json_decode(json_encode($myObj), true);
22echo "After conversion: \n";
23var_dump($myArray);
24?>
25
26Output:
27Before conversion:
28object(sample)#1 (2) {
29 ["var1"]=>
30 int(1000)
31 ["var2"]=>
32 string(6) "second"
33}
34
35After conversion:
36array(2) {
37 ["var1"]=>
38 int(1000)
39 ["var2"]=>
40 string(6) "second"
41}