1

Here's my recursive function:

function get_descendants($category_id) { global $descendants; $categories = get_ancestors($category_id); echo "get_ancestors($category_id);<br>"; // print_r($categories);exit; if (!is_array($categories)) return; foreach ($categories as $category) { $descendants[] = $category['id']; // Look for other leafs get_descendants($category['id']); } return $descendants; } function get_ancestors($parent_id) { global $db, $locale; $result = $db->query(" SELECT ... AND parent_id = $parent_id "); $categories = $result->fetch_all(MYSQLI_ASSOC); if ($result->num_rows > 0) { foreach ($categories as $category) $data[] = $category; return $data; } } 

The problem it's making the same call twice. So this is the result of running the code:

get_ancestors(8); get_ancestors(1); get_ancestors(2); get_ancestors(4); get_ancestors(5); get_ancestors(3); get_ancestors(6); get_ancestors(8); get_ancestors(1); get_ancestors(2); get_ancestors(4); get_ancestors(5); get_ancestors(3); get_ancestors(6); 

Where I should only see:

get_ancestors(8); get_ancestors(1); get_ancestors(2); get_ancestors(4); get_ancestors(5); get_ancestors(3); get_ancestors(6); 

What's wrong?

Thanks.

3
  • 1
    You probably should not declare your $descendants variable as global, otherwise it is never "cleared". Commented Jan 24, 2012 at 7:38
  • 1
    Your get_ancestors() method seems to return descendents instead of ancestors, shouldn't your get_ancestors() method have an other name, like get_childs() ? Commented Jan 24, 2012 at 7:54
  • That's correct. I'm intending to rename the function soon :) Commented Jan 24, 2012 at 8:13

1 Answer 1

2

The problem is that you don't want $descendants to be global.

You are sharing one variable across all the recursive calls. It really needs to be local for the logic you're using to be correct.

Instead of global $descendants; do $descendants = array();.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.