Hi guys! I'm new here! I have a problem that I can't solve, no matter how hard I try. Maybe you can help me? I have an array and a function to create a multi-level menu out of this array. Array is not multi-level. The problem: when I echo in function, everything works fine, but when I try to add all data to a string (to return it later), it doesn't add strings that have been created by recursion. Code Array structure: $menu[$row['id']] = array('title' => $row['title'], 'app' => $row['app'], 'parent' => $row['parent'], 'position' => $row['position']); Code (markup): $menu = html_menu($menu(array), $parent(parent's id), $active(some id), $multilevel(one-level vs multi), $html = ''(empty container)); Function: function html_menu($data, $parent, $active, $multilevel, $html) { foreach($data as $key => $value) { if($data[$key]['parent'] == $parent) { $activate = ($key == $active ? 'class="active"' : ""); $title = $data[$key]['title']; $html .= "<li>\n<a href=\"".MODULEURL.$data[$key]['app']."/index.php?action=open&id=".$key."\"".$activate.">".$title."</a>\n"; if($multilevel) html_menu($data, $key, $active, $multilevel, $html); $html .= "\n</li>\n"; } } return $html; } Code (markup): I hope you understand what I'm trying to do Please do not tell me to query recursively from mysql, cause it takes wayyyyyyyyy longer Thanks guys!
Try this one function html_menu($data, $parent, $active, $multilevel, $html) { foreach($data as $key => $value) { if($data[$key]['parent'] == $parent) { $activate = ($key == $active ? 'class="active"' : ""); $title = $data[$key]['title']; $html .= "<li>\n<a href=\"".MODULEURL.$data[$key]['app']."/index.php?action=open&id=".$key."\"".$activate.">".$title."</a>\n"; if($multilevel) { $html .= html_menu($data, $key, $active, $multilevel, $html); } $html .= "\n</li>\n"; } } return $html; } Code (markup):
can you paste the code when you actually call the function and how you try to display the result of the function?
on page: $sidebar['left'][0] = get_menu(false, $id , true); That calls out a function that gets all the results from DB and creates a non-multi-level array and passes it to the function above. That function returns the output (html formatted string), first function returns the string to sidebar['left']. The problem: recursive part of the function does not add created string to another string (i think .= does not work or something). Why I think that? Cause when switch $html .= "blah"; to echo "blah"; everything works. So --- wtf id going on with .= when function recursives itself? Thanks for helping