Friday, February 25, 2011

How to convert an object to an array recursively in PHP

Today, I had to spend some time digging exactly this issue. I had an object, and needed to convert it to an array(arrays in php are actually associative array)...
Below is the sample code to do that:

function convert_object_to_array(&$object)
{
if (!is_object($object) && !is_array($object))
return;
if (is_object($object))
$object = (array)($object);
foreach ($object as $key => $value) {
if (is_array($object[$key]) || is_object($object[$key])) {
convert_object_to_array($object[$key]);
}
}

}


$>



================================================================================
Now I will demonstrate its working:
Copy the code below to a file test.php and run the script: ($php test.php)





function convert_object_to_array(&$object)
{
if (!is_object($object) && !is_array($object))
return;
if (is_object($object))
$object = (array)($object);
foreach ($object as $key => $value) {
if (is_array($object[$key]) || is_object($object[$key])) {
convert_object_to_array($object[$key]);
}
}

}

class A
{

public $x ;
public $y;
public function __construct($a, $b)
{
$this->x = $a;
$this->y = $b;
}

}

class B
{
public $x;
public $y;
public $z;
public function __construct($m, $n, $p, $q)
{
$this->x = $m;
$this->y = $n;
$this->z = new A($p,$q);
}
}

$z = new B("B's x", "B's y", "A's x", "A's y");
echo "Look at the object dump below:";
print_r($z);

convert_object_to_array($z);
echo "\n=====================\n\n The object to array coneversion done \n";
print_r($z);
?>



/////
/*
Output is given below:

Look at the object dump below:B Object
(
[x] => B's x
[y] => B's y
[z] => A Object
(
[x] => A's x
[y] => A's y
)

)

=====================

The object to array coneversion done
Array
(
[x] => B's x
[y] => B's y
[z] => Array
(
[x] => A's x
[y] => A's y
)

)

No comments:

Post a Comment