Php convert object to array

0.61K views
no comments
28 Nov 2014 12:53 am

There is different way to access array and object many developers are use array instead object, if any a data get object and need to convert from object to array. Some are may be prefer to use object instead array, here is code example to quickly convert your large amount of object into array or array into object.

First we convert object to array

Just encode your $json_data to #json and then convert from json to array with function of json_decode and pass second parameter as TRUE for array.

$json_data = json_encode($object_data);
$array_data = json_decode($json_data,true);

The Second is convert array to object

In second step just invert the above code, encode array data with #json and  then pass second parameter in json_decode FALSE to return object

$json_data = json_encode($array_data);
$object_data = json_decode($json_data,false);

Here is define function to use them everywhere easily.

define function with name convert_arryobj we will use first parameter for data and second parameter for boolean if TRUE will pass function will convert into array if FALSE will be pass function will convert object.

function convert_arryobj($data,$bool){
	$data = json_encode($data);
	$data = json_decode($data,$bool);
	if(is_array($data) || is_object($data))
		return $data;
	}
	return false;
}

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>