0

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 that it prints everything regardless of what level it's at in the object?

thanks!

Charles
  • 50,943
  • 13
  • 104
  • 142
significance
  • 4,797
  • 8
  • 38
  • 57
  • Duplicate: http://stackoverflow.com/questions/2207599/multidimensional-array-iteration/2207739#2207739 – Gordon Mar 26 '10 at 15:28

2 Answers2

1

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.

symcbean
  • 47,736
  • 6
  • 59
  • 94
1

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);
    }
}
paulo
  • 11
  • 1