PHP convert an object to an array

For single dimensional array (array) $object works fine. Multi dimension object to array consist of private and protected members.

Example single dimensional:

// Cast to an array
$array = (array) $object;</code>

All objects to converted to associative arrays:

	function toArray($obj)
	{
	    if (is_object($obj)) $obj = (array)$obj;
	    if (is_array($obj)) {
	        $new = array();
	        foreach ($obj as $key => $val) {
	            $new[$key] = toArray($val);
	        }
	    } else {
	        $new = $obj;
	    }
	
	    return $new;
	}

Reference from here

By Keenlio, February 13, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


× 7 = fifty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>