场景:在一些商城或者分销中经常会用到:找出当前用户的所有上级和所有下级人员名单。
数据库结构:t_member表 字段:member_id, member_name, vip_recommend_user_id[推广者即上级]
代码实现:
//查一个用户的链路关系
public function member_link()
{
$member_name = input('member_name', '', 'trim');
if($member_name) {
$dbmember = db('member');
$row = $dbmember->where('member_name', $member_name)->column('member_name,member_id,vip_recommend_user_id');
$curr_member_id = $row[$member_name]['member_id'];
$vip_recommend_user_id = $row[$member_name]['vip_recommend_user_id'];//向上找链路关系
//第1种情况:当前传入用户为根用户,向下找链路关系
$down_link = '0 -> ' . '<span style="color:#FF0000">'. $member_name.'['.$curr_member_id.']' . '</span>' ;
$up_link = '<-' . '<span style="color:#FF0000">'.$member_name.'['.$curr_member_id.']' . '</span>' ;
while(true){
$row = $dbmember->where('vip_recommend_user_id', 'in', $curr_member_id)->column('member_id,member_name,vip_recommend_user_id');
if(empty($row)){
break;
}else{
$tmp = array_keys($row);
$curr_member_id = implode(',', $tmp);
$str = '';
foreach($row as $k => $v){
$str .= $v['member_name'].'['.$k.'],';
}
$down_link .= ' -> ' .trim($str, ',') ;
}
}
//第2种情况:当前传入用户为底级用户,向上找链路关系
while(true){
$row = $dbmember->where('member_id', 'in', $vip_recommend_user_id)->column('member_id,member_name,vip_recommend_user_id');
if(empty($row)){
$up_link .= '<-0';
break;
}else{
$tmp = array_column($row, 'vip_recommend_user_id');
$vip_recommend_user_id = implode(',', $tmp);
$str = '';
foreach($row as $k => $v){
$str .= '<-' . $v['member_name'] . '[' . $k . ']';
}
$up_link .= $str;
}
}
$tmp = explode('<-', $up_link);
$tmp2= array_reverse($tmp);
unset($tmp);
$up_link = implode('->', $tmp2);
ajaxOutFunc(200, ['down_link'=>'向下找链路关系:'.$down_link, 'up_link'=>'向上找链路关系:'.$up_link]);
}
return $this->fetch();
}
效果:
注:红色表示当前位置,所有的开始位置都以0为基准。
|