how do you write a function like print_r() that recursively prints objects?
i want to write a function that prints multi-dimensional objects which are text (or integers, etc.) into <span></span>
tags and arrays into unordered lists.
how do you make the function work recursively so th开发者_运维技巧at it prints everything regardless of what level it's at in the object?
thanks!
Objects can be treated as arrays - try using foreach....
function dump($obj, $prefix='')
{
foreach ($obj as $key=>$val) {
print "$prefix attribute $key is a " . gettype($val) . "=";
switch (gettype($val)) {
case 'string':
case 'boolean':
case 'resource':
case 'double':
case 'NULL':
var_export($val,true) . "\n";
break;
case 'object':
print "(class=" . get_class($val) . ")";
case 'array':
print "(";
dump($val, $prefix . ' ');
print ")\n";
default:
print "????\n";
}
}
}
C.
Or simpler, in case to print recursively the keys of an array,
function print_tree($array, $level = 0){
foreach($array as $key => $este){
echo str_pad($key, strlen($key) + $level, " ", STR_PAD_LEFT) . "\n";
if (is_array($este))
print_tree($este, $level+1);
}
}
精彩评论