There are times (like when dealing with simplexml) when you just wish you had an array that you can iterate over for whatever your reasons are (especially when dealing with variable structured multidimensional unpredictable input.) This is also a good example of recursive functions, simplification of difficult specialized problems, and how one might use a class to accomplish large tasks in an encapsulated fashion.
[coolcode]
/**
* A class for [N]ormalizing a [C]ontainer to an array
*
* This will class will take any type of variable container and return a normalized array
* For example this will take the output of simplexml_load_string and render it all into
* a multidimensional array.
*
*
*/
/**
*
*/
class nc2array {
private $original_container;
private $normalized_container;
/*
* Takes a variable, and builds a normalized comtainer out of it
*/
function __construct($container) {
$this->original_container=$container;
if ( is_object($container) ) {
$this->normalized_container=$this->recursive_parse_object($container);
} elseif ( is_array($container) ) {
$this->normalized_container=$this->recursive_parse_array($container);
} else {
$this->normalized_container[]=$container;
}
return($this->normalized_container);
}
/*
* takes an array and parses it recursively, passing objects off to recursive_parse_object
*/
function recursive_parse_array($array) {
foreach ( $array as $idx => $val ) {
if ( is_array($val) ) {
$rval[$idx]=$this->recursive_parse_array($val);
} elseif( is_object($val) ) {
$rval[$idx]=$this->recursive_parse_object($val);
} else {
$rval[$idx]=$val;
}
}
return($rval);
}
/*
* Takes an object and parses it recursively, passing arrays back off to recursive_parse_array
*/
function recursive_parse_object($obj) {
$vals=get_object_vars($obj);
while (list($idx, $val) = each($vals)) {
if ( is_object($val) ) {
$rval[$idx]=$this->recursive_parse_object($val);
} elseif ( is_array($val) ) {
$rval[$idx]=$this->recursive_parse_array($val);
} else {
$rval[$idx]=$val;
}
}
return($rval);
}
}
?>
[/coolcode]