PHP函数生成UL LI [英] PHP function generate UL LI
问题描述
我指的这个地址功能olLiTree
<一个href=\"http://stackoverflow.com/questions/753853/php-function-that-creates-a-nested-ul-li\">http://stackoverflow.com/questions/753853/php-function-that-creates-a-nested-ul-li
我有这个阵列
$树=
阵列(A=>阵列(B=>阵列(C=>C,D=>D),E=>阵列(F=>F ,G=>G)));
块引用>但不能使用此功能。
函数olLiTree($树)
{
呼应'&LT; UL&GT;';
的foreach($树$项目){
如果(is_array($项目)){
olLiTree($项目);
}其他{
呼应'&LT;立GT;',$项目,'&LT; /李&GT;';
}
}
呼应'&LT; / UL&GT;';
}生成
&LT; UL&GT;
&LT;李&gt;一种&LT; /李&GT;
&LT;立GT; b
&LT; UL&GT;
&LT;立GT; C&LT; /李&GT;
&LT;立GT; D&LT; /李&GT;
&LT; / UL&GT;
&LT; /李&GT;
&LT;立GT,E
&LT; UL&GT;
&LT;立GT;˚F
&LT; /李&GT;
&LT; / UL&GT;
&LT; /李&GT;
&LT; UL&GT;
&LT;立GT; G&LT; /李&GT;
&LT; / UL&GT;
&LT; / UL&GT;任何人可以帮助我解决这一问题?
感谢..解决方案函数olLiTree($树){
$ OUT ='&LT; UL&GT;'; 的foreach($树$关键=&GT; $值){
$ OUT ='&LT;立GT;'; 如果(is_array($值)){
$出去。= $键。 olLiTree($值);
}其他{
从$ = $价值。
} $ OUT ='&LT; /李&GT;';
} $ OUT ='&LT; / UL&GT;'; 返回$出;
}总是
收益
最终输出,不要回声
直接吧。你会感谢自己有一天当你发现,你的的情况不的希望回声
立即。 :)您可能希望将阵列结构改变这一点,因为它是多余的少(以上code工作):
$树=阵列('A','B','C'=&GT;阵列('CA','CB'),'D');
i'm referring this address for function olLiTree
http://stackoverflow.com/questions/753853/php-function-that-creates-a-nested-ul-li
i have this array
$tree = array("A"=>array("B"=>array("C"=>"C","D"=>"D"),"E"=>array("F"=>"F","G"=>"G")));
but not able to use this function
function olLiTree($tree) { echo '<ul>'; foreach($tree as $item) { if (is_array($item)) { olLiTree($item); } else { echo '<li>', $item, '</li>'; } } echo '</ul>'; }
to generate
<ul> <li>A</li> <li>B <ul> <li>C</li> <li>D</li> </ul> </li> <li>E <ul> <li>F </li> </ul> </li> <ul> <li>G</li> </ul> </ul>
can anybody help me to fix this? thanks..
解决方案function olLiTree($tree) { $out = '<ul>'; foreach($tree as $key => $value) { $out.= '<li>'; if (is_array($value)) { $out.= $key . olLiTree($value); } else { $out.= $value; } $out.= '</li>'; } $out.= '</ul>'; return $out; }
Always
return
the final output, don'techo
it directly. You'll thank yourself one day when you find a situation where you don't want toecho
it immediately. :)You might want to change the array structure to this, as it's less redundant (works with above code):
$tree = array('A', 'B', 'C' => array('CA', 'CB'), 'D');
这篇关于PHP函数生成UL LI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!