1

I have a user table with hierachical users. So users can have a parent user. I am trying to return an array of all child user ids of a certain user. My function returns "null". What's wrong?

public function userDownline($userid, $result = array()) {
    $dbconn = $this->DBase();
    $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
    if(count($children) > 0) {
        foreach($children As $k=>$v) {
            if(!in_array($v['id'], $result)) $result[] = $v['id'];
            $this->userDownline($v['id'], $result);
        }
    } else {
        return $result;
    }
}    

1 Answer 1

1

Of course it will return null, because you are in block if(count($children)) and there is no return from this.

I think you have to do something like this:

<?php
public function userDownline($userid, &$result = array())
{
    $dbconn = $this->DBase();
    $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
    if (count($children) > 0) {
        foreach ($children As $k => $v) {
            if (!in_array($v['id'], $result)) $result[] = $v['id'];
            $this->userDownline($v['id'], $result);
        }
    }
    return $result;
}

I added reference in function signature and move return out of the conditional block.

But this is really totaly inefficient way and dangerous(because of - out of memory, too many nesting level and other exceptions).

There are 2 better ways:

  1. Use https://neo4j.com/ - Graph Database - best option for your task.
  2. If you still wanna use only Sql DB - read about Nested set Model http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I added a "return" to the said line - now I get the first child (1 recordset, instead of many).
The mikehillyer site is awesome - thank you! +1 for this.
Great - &$result did the trick! Now it's working. Many thanks!

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.