是否可以获取可能链接到UserID1的所有用户?
例如:
UserID1引用UserID2和UserID5
UserID2引用了UserID3
UserID3引用了UserID4
结果在UserID1的页面上:
- + UserID2
- + UserID5
- ++ UserID3
- +++ UserID4
我目前的表现如何:
$user_data['id']=1;
$primary_referral_query=mysqli_query($conn, "SELECT username FROM users WHERE referrer=$user_data[id]");
while($primary_referral=mysqli_fetch_array($primary_referral_query))
{
echo '+'.$primary_referral['username'].'<br>';
}
$secondary_referral_query=mysqli_query($conn, "SELECT a.username, b.username, c.username AS users_c_username FROM users AS a, users AS b, users AS c WHERE b.referrer = a.id AND a.id <> b.id AND c.referrer = b.id AND a.id=$user_data[id]");
while($secondary_referral=mysqli_fetch_array($secondary_referral_query))
{
echo '++'.$secondary_referral['users_c_username'].'<br>';
}
答案 0 :(得分:0)
您存储分层数据的方法称为邻接列表(模型)。
您有不同的选择:
1)从数据库中读取所有数据,将其放入php数组并递归遍历
示例:https://stackoverflow.com/a/15307555/1948627
2)仅选择当前用户和后代,将其放入php数组并以递归方式遍历
SQL应如下所示:
SELECT u1.username as lev1, u2.username as lev2, u3.username AS as lev3, u4.username AS as lev4
FROM users AS u1
LEFT JOIN users AS u2 ON u2.referrer = u1.id
LEFT JOIN users AS u3 ON u3.referrer = u2.id
LEFT JOIN users AS u4 ON u4.referrer = u3.id
WHERE u1.id = 1;
我没有找到php代码的示例,但它应该更难,因为您收到的数据现在是多余的。另请注意:对于树中的每个新深度,您必须在数据库选择中添加一个JOIN。
3)递归PHP / MySQL
示例:https://stackoverflow.com/a/10994181/1948627
如果您没有太多数据,我会选择选项1。或者更好地选择另一种存储或检索数据的方式。
我最喜欢的方式是Closure Tables
关于嵌套集的另一个有趣的意见:https://stackoverflow.com/a/31642680/1948627