开发者

how do you write a function like print_r() that recursively prints objects?

开发者 https://www.devze.com 2022-12-24 01:54 出处:网络
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.

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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消