I worked on the recursive function today to create cfdump which give information about the object/array/structure in very neat and clean format. While applying recursive function to array in my implmentation, I was not able to show the nested levels of the elements in array.
Here is my array which I want to print
$tempArray=array(“info”=>array(“firstName”=>”vijay”,”lastName”=>”khambalkar”,”age”=>array(20,30,40)), “address”=>array(“Borivali”,”west”),”test”=>”just a test element”);
Output I was trying to print is
–vijay
–khambalkar
––20
––30
––40
–Borivali
–west
just a test element
I initial thought on using global varible which keeps track of the nested level. I thought over it and decide before each recursive call I will increment my variable, but in this case every time the global varible was just incrementing. As after coming to original level we need to decrement the global variable. So here is my final script which allowed me to print the expected output.
$tempArray=array(“info”=>array(“firstName”=>”vijay”,”lastName”=>”khambalkar”,”age”=>array(20,30,40)), “address”=>array(“Borivali”,”west”),”test”=>”just a test element”);
function showList($tempArray)
{
static $counter = 0; //Static varible count is defined to keep the track of the counter globally.
foreach($tempArray as $key=>$value)
{
if(is_array($value) || is_object($value))
{
$counter++; //This variable is incrementing each time functions get called recursively
showList($value);
$counter–; //When function is back, it simply decrement the value
}
else
{
echo str_repeat(“–”, $counter) . “$value <br>”; //This statement repeating the supplied character supplied by counter
}
}
}
showList($tempArray);
In my initial script counter was missing.
Overall good learning in recursive function. Although cfdump is not yet ready. Will do it some day later in this week