I believe that at some point everybody have already tried to convert an array to a object and if you search on Google.com you are going to find some great functions for that, but have you already tried to convert an object to an array?

The process is very simple, you just will need to cast the object to an array object.

Consider this class:

Class A
{
private field1;
public field2;
protected field3;
function __construct(){ field2 = 2;}
}

$objectA = new A();

To convert this to a array is simple, you will only need to cast the result into an array:
$converted = (array) $objectA; 

For the other way around is not that simple, but here’s a simple code that can do the process:

$obj = new stdClass();
foreach($array as $key => $value)
{
$obj->$key = $value;
}

Consider this for most of the one level associative arrays. For a multilevel array you will need a little better function and for arrays that are not associative, you must provide an name for each field because php does not accept variables initiated with a number.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]


Leave a Comment

You must be logged in to post a comment.

blank