setFetchMode(DB_FETCHMODE_ASSO...">

How do I call a recursive function in smarty?

$sql = "select menu_id , menu_name , parent_id from menu " ;
$dbc->setFetchMode(DB_FETCHMODE_ASSOC);
$res = $dbc->query($sql);
while($row = $res->fetchRow()){
    $menu[$row['parent_id']][$row['menu_id']] = $row['menu_name'];
}

function make_menu($parent)
{
    global $menu ;
    echo '<ul>';
    foreach($parent as $menu_id=>$menu_name)
    {
        echo '<li>'.$menu_name ; 
        if(isset($menu[$menu_id]))
        {
            make_menu($menu[$menu_id]) ;
        }
        echo '</li>';
    }
    echo '</ul>';
}
$P['menu_bilder_data'] = $menu[0] ; 
//menu :off
$smarty->register_function('make_menu' , 'make_menu') ;

      

ok I have this section of code to fetch and pass to smarty.

I have registered my function make_menu

as a custom function using smarty and in the template I have this code:

{make_menu parent_id=$P.menu_bilder_data}

      

I am passing an array $P

in an index file. It should work, but it doesn’t work because it’s a recursive function, it returns an array instead of the nested uls printed; how can i fix this problem?

+1


a source to share


1 answer


Problem

The $ Smarty-> register_function () and {make_menu parent_id = $ P.menu_bilder_data} function calls the function call ($ params, & $ smarty)
where $ params =

array(
  'parent_id' => array(
     0 => array(
       1 => > "menu item 1",
)

      

This is not the data structure that the function expects.

Decision

You can call the function without using register_function

{$P.menu_bilder_data|@make_menu}

      



Trumpet "|" will pass $ P ['menu_bilder_data'] as the first argument to the function. And "@" makes the pipe pass an array. Without "@", the function will be called for all elements in the array.

Only a hint

Change the parameter from $ parent (which is an array) to $ parent_id. All these menus are available from the global $ menu.

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>';
}

      

From smarty:

{0|make_menu}

      

+2


a source







All Articles