Asked 3 years ago
3 Feb 2021
Views 662

posted

how to convert Array to object in PHP ?

i have array which contain value like this for example

$testdata=array("one"=>1,"two"=>2);


i need to convert array to object , is there any simpler way . please suggest
rajiv

rajiv
answered Nov 30 '-1 00:00


to convert Multi Dimensions array to object , 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 )
shyam

shyam
answered Nov 30 '-1 00:00

Array to object


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
angeo

angeo
answered Nov 30 '-1 00:00

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


$obj = (object) array("one"=>1,"two"=>2);

noob

noob
answered Nov 30 '-1 00:00

json_encode and json_decode will work for the array to object


$car=array("car"=>array("name"=>"tesla"));
 
$car_json=json_encode($car);
$car_obj=json_decode($car_json));
 print_r($car_obj);


$car_obj will give you object now

stdClass Object ( [car] => stdClass Object ( [name] => tesla ) )
Post Answer