This is a situation where you would want to use recursion:
<?php
//Make a list from an array
function makeList($array) {
//Base case: an empty array produces no list
if (empty($array)) return '';
//Recursive Step: make a list with child lists
$output = '<ul>';
foreach ($array as $key => $subArray) {
$output .= '<li>' . $key . makeList($subArray) . '</li>';
}
$output .= '</ul>';
return $output;
}
$array = array("Apple"=>array(), "Banana"=>array(), "Tangerine"=>array("Pear"=>array("Walnut"=>array(), "Ice Cream"=>array(), "Candy"=>array()), "Nectar"=>array()), "Honey"=>array(), "Sweets"=>array());
echo makeList($array);
?>
I made some modifications that alter the formatting of the output with added whitespace, and also allows you to optionally pass in an array containing alternate keys (so you can for instance replace numeric ID’s with names):
function makeList($array, $depth=0, $key_map=FALSE) {
$whitespace = str_repeat("\ ", $depth*2);
//Base case: an empty array produces no list
if (empty($array)) return '';
//Recursive Step: make a list with child lists
$output = "$whitespace<ul>\
";
foreach ($array as $key => $subArray) {
$subList = makeList($subArray, $depth+1, $key_map);
if($key_map AND $key_map[$key]) $key = $key_map[$key];
if($subList) $output .= "$whitespace\ <li>" . $key . "\
" . $subList . "$whitespace\ </li>\
";
else $output .= "$whitespace\ <li>" . $key . $subList . "</li>\
";
}
$output .= "$whitespace</ul>\
";
return $output;
}
You’d have to convert that array to the format the makeList() function accepts. Make it a nested array, with the $key_map array containing the anchor text. e.g. $key_map = array(‘1’=>‘<a href=“url-1”>Category 1</a>’, …)