大师!首先,我花了半天时间在谷歌上搜索,但找不到解决方案。这是我第一次使用递归。希望有人能帮忙。
我有一个MySQL表,这是一种参考系统:
Table 'users'
ID SPONSORID
---------
1 2
2 1
3 1
4 1
... ...
有几件事需要记住:
- 用户1和2是彼此的赞助商/推荐人
- 每个用户可以有无限数量的引用
- 每个用户的推荐人也成为赞助商,并且可以拥有无限数量的推荐人
- 深度是无限的
任务是递归地构建一个单一"团队"的树,比如:
User 1
User 2
User 1
User 5
...
....
User 3
User 295
User 356
....
User 4
等等…
以下是我要做的:
$team = Array();
function build_team( $userID, $team ){
if ( !in_array($userID, $team ) :
// get 1st level of referals
// returns associative array ('id', 'login', 'sponsorid')
$referals = get_user_referals( $userID );
for ( $i=0; $i<count($referals); $i++ ) :
$team[] = $referals[$i];
build_team( $referals[$i]['id'] );
endfor;
endif;
}
还尝试将IF放入FOR块中,但它仍然处于无限循环中。据我所知,当没有深度级别时,我需要一个退出递归的条件,但我不明白如何计算/确定它。有什么建议吗?
将已经"构建"的用户id保存在某个地方。正如你自己所说——"用户1和用户2是彼此的赞助商/推荐人。",所以这是你的无限循环。
类似的东西
if (!in_array($userId, $already_looped_users){
//continue loop...
}
添加一些代码:
$team = Array();
function build_team( $userID, $team ){
if ( !in_array($userID, $team ) :
// get 1st level of referals
// returns associative array ('id', 'login', 'sponsorid')
$referals = get_user_referals( $userID );
if (count($referals) > 0){ //added this line
for ( $i=0; $i<count($referals); $i++ ) :
$team[] = $referals[$i];
$team[$referals[$i] = build_team( $referals[$i]['id'], $team ); // i've edited this line
endfor;
return $team;
}
endif;
}