How to Create a Nestled List from a Multidimensional Array in PHP

Today’s snippet is a little PHP function that you can use to convert a nestled array to a nestled list.

[php]
<?php
function ims_array_lists(array $Array){
$output = ‘<ul>’."n";
foreach($Array as $Key => $Value){
$output .= "<li><strong>{$Key}: </strong>";
if(is_array($Value)){
$output .= ims_array_lists($Value);
}else{
$output .= $Value;
}
$output .= ‘</li>’."n";
}
$output .= ‘</ul>’."n";
return $output;
}
?>
[/php]

Usage example:

[php]
<?php

$marks = array(
"mohammad" => array ( "physics" => array("Branch One"=> 67, "Branch Two" => array ("Sub1" => array("Branch One"=> 67, "Branch Two" =>999),"Sub2" => 96)), "maths" => 30, "chemistry" => 39 ),
"qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 )
);

print_r (ims_array_lists($marks));
?>

[/php]

Will generate the following HTML markup;

[html]
<ul>
<li><strong>mohammad: </strong>
<ul>
<li><strong>physics: </strong>
<ul>
<li><strong>Branch One: </strong>67</li>
<li><strong>Branch Two: </strong><ul>
<li><strong>Sub1: </strong><ul>
<li><strong>Branch One: </strong>67</li>
<li><strong>Branch Two: </strong>999</li>
</ul>
</li>
<li><strong>Sub2: </strong>96</li>
</ul>
</li>
</ul>
</li>
<li><strong>maths: </strong>30</li>
<li><strong>chemistry: </strong>39</li>
</ul>
</li>
<li><strong>qadir: </strong>
<ul>
<li><strong>physics: </strong>30</li>
<li><strong>maths: </strong>32</li>
<li><strong>chemistry: </strong>29</li>
</ul>
</li>
<li><strong>zara: </strong>
<ul>
<li><strong>physics: </strong>31</li>
<li><strong>maths: </strong>22</li>
<li><strong>chemistry: </strong>39</li>
</ul>
</li>
</ul>
[/html]