PHP Script to print nested array
Here is a script that will allow you to print a nested array upto any level. Can I request you to please review this and let me know how this can be further optimized.
$array["sunil"] = "Bhatia"; $array[0] = array("one"=>"two",array(1,2,3,array(4,5,6))); $array["sunil2"] = "Bhatia2"; processArray($array); $count=0; function processArray($array) { global $count; $count++; //this variable is for calculating tab space if(is_array($array) === true) { foreach($array as $key => $value) { if(is_array($array[$key]) === true) { processArray($array[$key]); } else { for($i = 1 ; $i < $count ; $i++) echo " "; //change this to space ' ' if running from CLI echo $value."<br />"; } } } $count--; }
Related Posts on PHP5 Tutorial – Object Oriented Programming (OOPS)
- PHP5 Tutorial – Learn to create a PHP5 Class
- PHP5 Tutorial – Learn to Create a PHP5 Class Object
- PHP5 Tutorial – Defining Attributes of a PHP5 Class
- PHP5 Tutorial – Defining Methods of a PHP5 Class
- PHP5 Tutorial – Creating a PHP5 Constructor __construct()
- PHP5 Tutorial OOPS – Creating a PHP5 Destructor __destruct()
- PHP5 Tutorial OOPS – PHP5 Class Access Specifiers – public, private and protected
- PHP5 Tutorial – $this variable explained
- PHP5 Tutorial – instanceOf Operator Explained
- PHP5 Tutorial – Defining Class Constants
- PHP5 Tutorial – Magic Methods – __toString() method
- PHP5 Tutorial – Magic Methods – __get() and __set()
- PHP5 Tutorial – Magic Methods – __isset() and __unset()
- PHP5 Tutorial – Magic Methods – __call() method
- PHP5 Tutorial – Magic Methods – __autoload() method
- PHP5 Tutorial – Magic Methods – __sleep() and __wakeup()
- PHP5 Tutorial – Magic Methods – __clone() method
Categories: PHP, PHP Code Examples
Only had a short look at your code, but I suggest to have a look at “array_walk_recursive” manual
I see no problem with it, except for maybe you could do away with printing non-breaking spaces and replace them with the ‘\t’ control character for tabs.
The for() on line 22 is the only thing that stands out as possibly unnecessary, or as something that could be optimised, but I can’t think of how to do so at the moment so I’ll let it slide.
hehe.
I assume you are just trying to do this as a more interface-friendly print_r()?
Correction to my previous comment: array_walk_recursive doesn’t exactly help here as it doesn’t work with associative arrays the way I expected.
function processArray2($array){
if (is_array($array)){
array_map(‘processArray2′, $array);
} else {
echo ”.$array;
}
}
Delete my comments … forgot about the indents and it doesn’t quite work for the last bit:
$space = ”;
processArray2($array);
function processArray2($array){
global $space;
if (is_array($array)){
$space .= ‘ ’;
array_map(‘processArray2′, $array);
} else {
echo $space.$array.”;
}
}