2017-01-22 79 views
1

我有一个用户表和分层用户。所以用户可以有一个父用户。我正在尝试返回某个用户的所有子用户ID的数组。 我的函数返回“null”。怎么了?concat tree hierarchie在递归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); 
     } 
    } else { 
     return $result; 
    } 
}  

回答

1

当然,它会返回null,因为你在块if(count($ children))并且没有从这返回。

我认为你必须做这样的事情:

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

我加入的功能特征参考和移动回了条件块的。

但是这实际上是非常低效的方式并且很危险(因为 - 内存不足,嵌套层次太多以及其他例外)。

有2点更好的方法:

  1. 使用https://neo4j.com/ - 图形数据库 - 为您的任务最好的选择。
  2. 如果你仍然想使用只有SQL数据库 - 了解组嵌套模式http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
+0

谢谢 - 我加了一个“回”到上述线路 - 现在我得到了第一个孩子(1条记录,而不是许多)。 – Gerfried

+0

mikehillyer网站真棒 - 谢谢!为此+1。 – Gerfried

+0

我再次看了一遍,并用代码更新了我的答案。 – vuliad