I' am trying this for a long time now. The function below returns only 1 result where as it should return 3 results.
I have checked the database, the database returns results in a loop fine that means database part is okay, its somewhere in the function that am doing wrong.
//function that generates the URI from the database
function generate_uri( $menu_id = 0, $array = '' ){
global $db;
$array = array();
if( !empty($menu_id) ){
$db->where('menu_id', $menu_id);
$menu = $db->ObjectBuilder()->getOne('menu');
$menu_parent = $menu->menu_parent;
$menu_slug = $menu->menu_slug;
$array[] = $menu_slug;
generate_uri($menu_parent, $array);
}
return $array;
}
//Calling the function with a parameter of 3
var_dump(generate_uri(3));
Output
array(1) { [0]=> string(15) "photo-gallery-1" }
Should Return
array(1) { [0]=> string(15) "photo-gallery-1" [1]=> string(12) "photo-gallery" [2]=> string(9) "resources"}
Every time you call the function, you set $array
empty: $array = array();
Another problem is that you are not getting the return of the function inside the if statement. Change this line:
generate_uri($menu_parent, $array);
To this:
$array = generate_uri($menu_parent, $array);
So, the function should be something like this:
function generate_uri($menu_id = 0, $array = '') {
global $db;
if (!empty($menu_id)) {
$db->where('menu_id', $menu_id);
$menu = $db->ObjectBuilder()->getOne('menu');
$menu_parent = $menu->menu_parent;
$menu_slug = $menu->menu_slug;
$array[] = $menu_slug;
$array = generate_uri($menu_parent, $array);
}
return $array;
}
You're redeclaring $array
at each recursive call, so it gets reinitialised each time. Try declaring it before calling generate_uri()
and passing it as the second argument:
$array = array();
var_dump(generate_uri(3, $array));
And don't forget to remove it from inside the function.