array2object() function
This is something that I don't want to lose, after cracking my head for hours, hence it's placed here.
This is a function which I couldn't find on the Net, a smart function to convert arrays to objects while retaining itself as arrays if necessary:
<?php
/**
* Just process non-numeric arrays. If the array has both numeric and string arrays,
* then remove numeric ones while retaining string arrays. Recurse into objects as well
* to check for any possible conversion.
**/
function array2object ($arg_array) {
if (is_array($arg_array)) {
$keys = array_keys($arg_array);
foreach ($keys as $key) {
if (is_numeric($key)) $has_number = true;
if (is_string($key)) $has_string = true;
if (is_object($key)) $has_object = true;
};
if (isset($has_number) and !isset($has_string)) {
foreach ($arg_array as $key=>$value) {
$tmp[] = array2object($value);
}
}
elseif (isset($has_string)) {
foreach ($arg_array as $key=>$value) {
if (is_string($key))
$tmp->$key = array2object($value);
}
}
} elseif (is_object($arg_array)) {
foreach ($arg_array as $key => $value)
if (is_array($value) or is_object($value))
$tmp->$key = array2object($value);
else
$tmp->$key = $value;
}
else {
$tmp = $arg_array;
};
return $tmp; //return the object
};
?>
Phew!
0 Comments:
Post a Comment
<< Home