简体   繁体   English

php动态函数列表

[英]php dynamic function for list

I am trying to make dynamic function where user can create list without adding <ul> <li> tag. 我试图使动态功能,用户可以在不添加<ul> <li>标记的情况下创建列表。

here is my function 这是我的功能

function the_main_nav($navlinks){
        echo '<nav>';
        echo '<ul>';

        $menuitem = $navlinks;
        $pieces = explode(",",$menuitem);

        $i=$navlinks;
        while($i==','){ 
            echo '<li>' . $pieces[$i] . '</li>';
            $i++;
        }

        echo '</ul>';
        echo '</nav>';      
    }

This is my template tag the_main_nav('1,2,3,44 5'); 这是我的模板标签the_main_nav('1,2,3,44 5');

But its going into endless loop with error. 但是它陷入了无休止的循环,并伴有错误。 I want auto generate <li> after each ',' commma. 我想在每个','逗号后自动生成<li> Also if possible I want anchor link within the list so it can be linked with the page. 另外,如果可能的话,我想在列表中添加锚链接,以便可以与页面链接。

Instead of while loop, use foreach : 代替while循环,使用foreach

foreach ( $pieces as $piece ) {
  echo '<li>' . $piece . '</li>';
}

Yep, using a foreach can be cool, but your error is in your logical view. 是的,使用foreach可能很酷,但是您的错误出在逻辑视图中。 If I look at your algorithm I see : Write some open tags store my argument into a new variable called $menuitem create an array from $menuitem each time you find a "," and store it in $pieces store my argument into a new variable called $i now while $i is equal to the char "," (which is allways false) write my subtags 如果我看一下您的算法,则会看到:编写一些打开的标签,将参数存储到一个名为$ menuitem的新变量中,每次发现“”时都从$ menuitem创建一个数组,并将其存储在$ pieces中,将参数存储到一个新变量中现在称为$ i,而$ i等于char“,”(总是错误的)写我的子标签

after that write end tags. 之后写完结束标签。

You do not course your array. 您不设置阵列。 A foreach loop will do it. 一个foreach循环会做到这一点。 But to correct your code you must understand that $i must take as value the indexes of the array, so 0,1,2,3... 但是要纠正您的代码,您必须了解$ i必须将数组的索引作为值,所以0,1,2,3 ...

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

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