Asked 8 years ago
12 Nov 2016
Views 10247
ching

ching posted

how to convert stdClass to Array and Array to stdClass in php ?

How to convert stdClass to Array and Array to stdClass in php
angeo

angeo
answered Nov 30 '-1 00:00


to convert Multi Dimensions array to stdClass , use following function


function MultiDimensionsArrayToObject($ar){
	$r=new stdclass();
	foreach($ar as $key=>$value){
		if(is_array($value)){
		$r->$key=MultiDimensionsArrayToObject($value);			
		}else {
		$r->$key=$value;			
		}

	}
	return $r;
}


$a=array("one"=>array("third"),"two");
 
$result=MultiDimensionsArrayToObject($a);
print_r($result);


result will be multi dimension object

stdClass Object ( [one] => stdClass Object ( [0] => third ) [0] => two )
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

stdClass to Array and Array to stdClass in php ,

stdClass to Array


$data = new stdclass();
$data->name="data";

print_r($data);

$k=get_object_vars($data);
 
print_r($k);



when you call get_object_vars , it will return array of the object variables ' array which means it convert stdclass to array .

Array to stdClass


function ArrayToObject($ar){
	$r=new stdclass();
	foreach($ar as $key=>$value){
		$r->$key=$value;
	}
	return $r;
}
$ar=array("data","is","more","important");
$r=ArrayToObject($ar);
print_r($r);


its simple function ArrayToObject which convert array to object means stdClass
Rasi

Rasi
answered Nov 30 '-1 00:00


to convert array to stdClass or object , simply convert it to object cast. type conversion is the solution

$obj = (object) array('1' => 'name');

(object) convert array to object

to convert object (stdClass) to array , simply convert it to array cast , its called type conversion

$d=new stdClass();
$d->start=1;
print_r((array)$d);

(array) convert object to array.
QuickIos

QuickIos
answered Jun 25 '22 00:00

to convert stdClass object to Array use json_encode and json_decode

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


json_encode convert the object to a string
and again decode JSON string to the array by json_decode.
Post Answer