Create ul and li using multidimensional array in php

I have the following array:

$ tree_array

When I do var_dump, I get:

array(6) { [0]=> string(23) "$100,000 Cash Flow 2013" [1]=> array(6) { [0]=> string(1) "2" ["Goal_ID"]=> string(1) "2" [1]=> string(13) "Sell Iron Oak" ["Opportunity"]=> string(13) "Sell Iron Oak" [2]=> string(2) "10" ["OID"]=> string(2) "10" } [2]=> array(2) { [0]=> string(32) "ask her if she would like to buy" ["Activity"]=> string(32) "ask her if she would like to buy" } [3]=> array(6) { [0]=> string(1) "2" ["Goal_ID"]=> string(1) "2" [1]=> string(8) "Sell Car" ["Opportunity"]=> string(8) "Sell Car" [2]=> string(2) "11" ["OID"]=> string(2) "11" } [4]=> array(2) { [0]=> string(52) "Call Roy back to see if he would like to purchase it" ["Activity"]=> string(52) "Call Roy back to see if he would like to purchase it" } [5]=> array(1) { ["tot_opp"]=> NULL } } 

My ultimate goal is to create unordered lists and lists (ul, li) with this data. Adding a database to the array will add more data, so it will continue to grow. My goal is to iterate over the array and create its next code and be able to continue to create lists as the data grows. I am new to php and don't know how to do this.

 <ul> <li>$100,000 Cash Flow 2013</li> <ul> <li>Sell Iron Oak</li> <ul> <li>ask her if she would like to buy</li> </ul> <ul> <li>Sell Car</li> </ul>etc... 

Any help would be greatly appreciated! Thank you in advance!

+6
source share
2 answers

This seems to be a pretty simple recursion:

 function arrayToList($in) { echo "<ul>"; foreach($in as $v) { if( is_array($v)) arrayToList($v); else echo '<li>' . $v . '</li>'; } echo "</ul>"; } 

It looks like you have multiple duplicate values. Are you mysql_fetch_array ? You should use mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.

+1
source

To do this, you need a recursive function, not a loop. That way, it will handle any depth of your original array.

 function make_list($arr) { $return = '<ul>'; foreach ($arr as $item) { $return .= '<li>' . (is_array($item) ? make_list($item) : $item) . '</li>'; } $return .= '</ul>'; return $return; } echo make_list($source_array); 
+1
source

All Articles