views:

645

answers:

1
$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 retrieve and pass to smarty.

I have registered my make_menu function as a custom user function with smarty, and in the template i have this code:

{make_menu parent_id=$P.menu_bilder_data}

I'm passing $P array in index file. It must work but it gives me nothing because it's a recursive function, it returns an array instead of printed nested uls; how can i fix this issue?

+1  A: 

The problem

The $Smarty->register_function() and {make_menu parent_id=$P.menu_bilder_data} causes the funtion to be called with ($params, &$smarty)
where $params =

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

This is not the data-structure the function excpects.

Solution

You could call the function without using "register_function"

{$P.menu_bilder_data|@make_menu}

The pipe "|" will pass the $P['menu_bilder_data'] as first argument of the function. And the "@" causes the pipe to pass the array. Without the "@" the function would be called for all elements in the array.

Just a tip

Change the parameter from $parent (which is an array) to $parent_id, All menu data is 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}
Bob Fanger