简体   繁体   English

使用php中的多维数组创建ul和li

[英]create ul and li using a multidimensional array in php

I have the following array: 我有以下数组:

$tree_array $ tree_array

When I do a var_dump, I get: 当我执行var_dump时,我得到:

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. 我的最终目标是使用此数据创建无序列表和列表(ul,li)。 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. 我是php的新手,不确定如何做到这一点。

<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! 先感谢您!

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 ? 您正在使用mysql_fetch_array吗? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array. 您应该使用mysql_fetch_assoc还是mysql_fetch_row这取决于您需要关联数组还是索引数组。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM