I have the array below which I would like to output in a specific HTML list format.
My PHP array is as follow:
Array
(
[MAIN] => Master Product
[ID1] => Array
(
[0] => Product 1
)
[ID2] => Array
(
[0] => Product 2
[ID3] => Array
(
[0] => Product 3
)
[ID4] => Array
(
[0] => Product 4
)
)
)
The HTML list format I am looking for is as follows.
<ul id="treeview">
<li>Master Product
<ul>
<li>Product 1</li>
<li>Product 2
<ul>
<li>Product 3</li>
<li>Product 4</li>
</ul>
</li>
</ul>
</li>
</ul>
Any help would be appreciated.
Try this on for size:
function recurseTree($var){
$out = '<li>';
foreach($var as $v){
if(is_array($v)){
$out .= '<ul>'.recurseTree($v).'</ul>';
}else{
$out .= $v;
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($yourDataArrayHere).'</ul>';
$data = array(); // your data
function toUL($data=false, $flatten=false){
$response = '<ul>';
if(false !== $data) {
foreach($data as $key=>$val) {
$response.= '<li>';
if(!is_array($val)) {
$response.= $val;
} else {
if(!$flatten){
$response.= toUL($val);
} else {
// pulls the sub array into the current list context
$response.= substr($response,0,strlen($response)-5) . toUL($val);
}
}
$response.= '</li>';
}
}
$response.= '</ul>';
return $response;
}
// Test #1 -- named values echo toUL(array('a'=>'b','c'=>'d','e'=>array('f'=>'g'))); // Result #1
// Test #2 -- value lists echo toUL(array('a','b','c',array('d','e','f'))); // Result #2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With