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?
a source to share
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}
a source to share