Php 消除复发
我有一个功能,它工作得很好。我想问一下,是否可以保存功能但删除递归:Php 消除复发,php,recursion,Php,Recursion,我有一个功能,它工作得很好。我想问一下,是否可以保存功能但删除递归: public static function GenerateNavHTML($items, $tabs = '') { $html = !strlen($tabs) ? $tabs.'<ul class="dd-list">' : $tabs.'<ul>'; foreach($items as $it
public static function GenerateNavHTML($items, $tabs = '') {
$html = !strlen($tabs) ?
$tabs.'<ul class="dd-list">' :
$tabs.'<ul>';
foreach($items as $item) {
$item = (object)$item;
$html .= $tabs." ".'<li class="dd-item" data-id="'.(int)$item->id.'">';
$html .= '<div class="dd-handle">Drag</div>';
$html .= '<div class="dd-content">
<span class="title">'.(string)$item->name.'</span>
<div id="action" class="btn-group pull-right">
<button type="button" class="btn btn-primary btn-xs" title="Edit category" data-action="edit" data-id="'.(int)$item->id.'" data-category="'.(string)$item->name.'"><i class="fa fa-edit"></i></button>
<button type="button" class="btn btn-warning btn-xs" title="Delete category and all nested categories" data-action="delete" data-id="'.(int)$item->id.'" data-category="'.(string)$item->name.'"><i class="fa fa-close"></i></button>
</div>
</div>';
if(isset($item->children[0])) {
$html .= self::GenerateNavHTML($item->children, $tabs." ");
}
$html .= '</li>';
}
$html .= $tabs.'</ul>';
return $html;
}
公共静态函数GenerateNavHTML($items,$tabs=''){
$html=!strlen($tabs)?
$tabs.“”:
$tabs.“”;
foreach($items作为$item){
$item=(对象)$item;
$html.=$tabs.“”- ”;
$html.='Drag';
$html.='
“.(字符串)$item->name”
';
if(设置($item->children[0])){
$html.=self::GenerateNavHTML($item->children,$tabs“);
}
$html.='
';
}
$html.=$tabs.“
”;
返回$html;
}
您可以考虑为此使用队列。如果我理解正确,您的$item可以有多个子项,并且每个子项都需要类似的处理(for循环等)。您可以使用SplQueue并在找到每个项目后立即将其放入队列中。以下是psuedo代码:
$itemQ = queue of all top level items
foreach $item in $itemQ
//do processing here
if $item->children
$itemQ.add( $item->children)
为什么要删除
递归
?另一种观点。是否可能?递归
允许此函数无限深入列表,只要它们是子元素。这是最优雅的解决方案,因为如果没有递归,您将需要编写大量的foreach
循环,即如果您的列表是50个级别,您将需要50个相同代码的循环,这太愚蠢了。我知道我们可以使用while和每个语法来完成此操作。