create ul and li using a multidimensional array in

2019-06-19 14:58发布

问题:

I have the following array:

$tree_array

When I do a 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 end goal is to create unordered lists and lists (ul, li) with this data. There will be more data added to the array as the database gets updated, so it will keep growing. My goal is to loop through the array and have it create the following code and be able to keep creating lists as the data grows. I am new to php and not sure how to accomplish 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 will be greatly appreciated! Thank you in advance!

回答1:

You need a recursive function for that, not a loop. This way it will handle any depth of your source 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);


回答2:

Seems like a simple enough recursion to me:

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 some duplicate values up there. Are you using mysql_fetch_array? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.