PHP递归级别
我有递归函数。有一个层次结构的用户结构。我将用户 ID 发送到我的函数,它应该找到此下的所有用户。函数返回所有关联用户的数组。我的任务是找到该用户的级别。
例如:
User1
/ \
User2 User3
/ \ \
User4 User5 User6
用户1的级别为0。 User2、User3 的级别为 1。 User4、User5、User6 的级别为 2。 我怎样才能在递归中找到这个? 这是我的代码:
private function getAssociates($userId) {
global $generation;
global $usersUnder;
if (!isset($generation)) {
$generation = 1;
}
$userDb = new Lyf_DB_Table('user');
$associatesSelect = $userDb->Select();
$associatesSelect -> from('user', array('id'))->where('enroller_id = ?', $userId);
$associates = $userDb->fetchAll($associatesSelect)->toArray();
if (!empty($associates)) {
foreach ($associates as $associate) {
$usersUnder[$generation] = $associate['id'];
$this->getAssociates($associate['id']);
}
}
return $usersUnder;
}
I have the recursion function. There are an hierarchy users structure. I send a user id to my function and it should find all user under this. Function returns an array of all associates users. My task is to find a levels of this users.
For example:
User1
/ \
User2 User3
/ \ \
User4 User5 User6
User1 have level 0.
User2, User3 have level 1.
User4, User5, User6 have level 2.
How can I find this in my recursion?
It is my code:
private function getAssociates($userId) {
global $generation;
global $usersUnder;
if (!isset($generation)) {
$generation = 1;
}
$userDb = new Lyf_DB_Table('user');
$associatesSelect = $userDb->Select();
$associatesSelect -> from('user', array('id'))->where('enroller_id = ?', $userId);
$associates = $userDb->fetchAll($associatesSelect)->toArray();
if (!empty($associates)) {
foreach ($associates as $associate) {
$usersUnder[$generation] = $associate['id'];
$this->getAssociates($associate['id']);
}
}
return $usersUnder;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向您的
getAssociates()
函数添加一个额外的参数:当您处理树的该级别时,将
$level
与其余用户数据一起存储,然后递归到函数中:当您最初调用该函数来启动此过程时,为
$level
传入0
,或者将其留空并让 PHP 分配默认值 (也是0
)。Add an extra parameter to your
getAssociates()
function:and when you're processing that level of the tree, store the
$level
with the rest of the user data, then recurse into the function with:and when you initially call the function to start this process, pass in
0
for$level
, or leave it blank and let PHP assign the default (also0
).看一下迭代器:
Have a look at iterators:
简单,但我不在 zend 中工作,所以我不能告诉你代码,但我可以给你描述
make 函数
,然后它们调用
easy but I don't work in zend so I can't tell you code but I can give you description
make function
and them call