将递归函数从Php更改为smarty?

时间:2013-02-07 01:31:54

标签: function recursion smarty3

我的问题 我有无尽的菜单 代码

        $result=db::query_tpv("SELECT * FROM  tpv_link");
while($row = db::fetch_array($result,'assoc'))
 {

$menu[$row['parent_id']][$row['id_link']] = $row['name_link'];

}
function make_menu($parent_id)
{global $menu;if (!isset($menu[$parent_id])) {return;}
$nodes = $menu[$parent_id];
echo '<ul>';
foreach($nodes as $menu_id => $menu_name)
{
echo '<li>'.$menu_name ;
make_menu($menu_id) ;
echo '</li>';
}
echo '</ul>';
}

它在samrty工作也是由{0 | make_menu} ,但我想取消此功能并在smarty中更改为此(定义$ menu)

{function name=menu level=0}
        <ul>
            {foreach $data as $items}
                <li>
                    <a href="{$items.url}">
                        {$items.title}
                    </a>
                    {if is_array($items.submenu)}
                        {menu data=$items.submenu level=$level+1}
                    {/if}
                </li>
            {/foreach}
        </ul>
    {/function}
{menu data=$menuItems}

how to foreach an array variable created with recursive function in Smarty 但它不起作用.....

1 个答案:

答案 0 :(得分:0)

你好我在3天后找到解决方案

下面

------------首先你要查询你的表---------- 例如:

    $result=db::query_tpv("SELECT * FROM  tpv_link");
  while($row = db::fetch_array($result,'assoc'))
 {

 $menu[]=$row ;
 }

------------ Secound使用此函数(用于制作你的pyrimd数组)---------- ------------注意改变id,parentid ----------

   function buildTree(array $elements, $parentId = 0) {
$branch = array();

foreach ($elements as $element) {
    if ($element['parent_id'] == $parentId) {
        $children = buildTree($elements, $element['id_link']);
        if ($children) {
            $element['children'] = $children;
        }
        $branch[] = $element;
    }
}

return $branch;
}

------------------- Smarty模板之前--------------------

$tree = buildTree($menu);//$menu array all data From Query
$smarty->assign('menu',$tree);

------------------在聪明的模板中------------------------- < / p>

   {function name=menu level=0}
        <ul>
            {foreach $data as $items}
                <li>
                    <a href="{$items.url}">
                        {$items.name_link}
                    </a>
                    {if $items.children}
                        {menu data=$items.children level=$level+1}
                    {/if}
                </li>
            {/foreach}
        </ul>
    {/function}


    {menu data=$menu}