stdclass object to array php code example

Example 1: php stdclass to array

// The manual specifies the second argument of json_decode as:
//	 assoc
//		When TRUE, returned objects will be converted into associative arrays.


$array = json_decode(json_encode($booking), true);

Example 2: php convert array to object

$object = (object) $array;

Example 3: php create object

$x = (object) [
    'a' => 'test',
    'b' => 'test2',
    'c' => 'test3'
];
var_dump($x);

/*
object(stdClass)#1 (3) {
  ["a"]=>
  string(4) "test"
  ["b"]=>
  string(5) "test2"
  ["c"]=>
  string(5) "test3"
}
*/

Example 4: php convert object to array

$person = new stdClass();
$person->firstName = "Taylor";
$person->age = 32;

//Convert Single-Dimention Object to array
$personArray = (array) $person;

//Convert Multi-Dimentional Object to Array
$personArray = objectToArray($person);
function objectToArray ($object) {
    if(!is_object($object) && !is_array($object)){
    	return $object;
    }
    return array_map('objectToArray', (array) $object);
}

Example 5: convert object to array php

<?php 
class sample { 
      
    /* Member variables */
    var $var1; 
    var $var2; 
      
    function __construct( $par1, $par2 )  
    { 
        $this->var1 = $par1; 
        $this->var2 = $par2; 
    } 
} 
  
// Creating the object 
$myObj = new sample(1000, "second"); 
echo "Before conversion: \n"; 
var_dump($myObj); 
  
// Converting object to associative array 
$myArray = json_decode(json_encode($myObj), true); 
echo "After conversion: \n"; 
var_dump($myArray); 
?> 
  
Output:
Before conversion: 
object(sample)#1 (2) {
  ["var1"]=>
  int(1000)
  ["var2"]=>
  string(6) "second"
}

After conversion: 
array(2) {
  ["var1"]=>
  int(1000)
  ["var2"]=>
  string(6) "second"
}

Example 6: php object(stdclass) to array

$array = json_decode(json_encode($object), true);