0

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"}
2
  • Did u try to this print_r(generate_uri(3));? instead of var_dump Commented Sep 5, 2015 at 15:37
  • @Grald yes I have tried it, still the same result. Commented Sep 5, 2015 at 15:39

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you very much you are awesome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.