编写查询实现玩家按积分匹配 差值≤10可匹配否则无匹配
玩家匹配功能实现方案
需求说明
- 匹配规则:优先匹配积分完全相同的玩家,无同积分匹配对象时可匹配积分差值≤10的玩家,积分差值超过10则标记为
match not found - 玩家表字段:id、player(玩家名)、points(积分),现有9条示例玩家数据
- 输出要求:每条匹配记录占一行,包含id、玩家1名称、玩家1积分、玩家2名称、玩家2积分,无匹配的对应位置显示
match not found
代码修改实现
HTML部分(调整表头适配输出字段)
<table class="table table-bordered table-hover table-striped is-narrow is-hoverable"> <thead> <tr> <th class="bg-danger text-center">id</th> <th class="bg-danger text-center">玩家1名称</th> <th class="bg-danger text-center">玩家1积分</th> <th class="bg-danger text-center">玩家2名称</th> <th class="bg-danger text-center">玩家2积分</th> </tr> </thead> <tbody id="playerdisplay"> </tbody> </table> <!-- 触发匹配的按钮,确保id为player --> <button id="player" class="btn btn-primary">查询匹配</button>
前端JS部分(原有逻辑可保留,仅需确保接口路径正确)
$(document).on('click','#player',function(){ $.ajax({ url:"<?=site_url('controller/players')?>", method:"POST", dataType:'json', success:function(data){ $('#playerdisplay').html(data); } }) })
后端Controller部分(新增匹配逻辑,修复原HTML拼接错误)
function players(){ $players = $this->player_model->playerss(); $player_arr = json_decode(json_encode($players), true); // 转成数组方便处理 $total = count($player_arr); $visited = array_fill(0, $total, 0); // 标记已匹配的玩家,避免重复匹配 $row = ''; $match_id = 1; for($i=0; $i<$total; $i++){ if($visited[$i] == 1) continue; $p1 = $player_arr[$i]; $match_p2 = null; // 第一步:优先找积分完全相同的未匹配玩家 for($j=$i+1; $j<$total; $j++){ if($visited[$j] == 0 && $player_arr[$j]['points'] == $p1['points']){ $match_p2 = $player_arr[$j]; $visited[$j] = 1; break; } } // 第二步:没有同积分的,找积分差值≤10的未匹配玩家 if($match_p2 == null){ for($j=$i+1; $j<$total; $j++){ if($visited[$j] == 0 && abs($player_arr[$j]['points'] - $p1['points']) <= 10){ $match_p2 = $player_arr[$j]; $visited[$j] = 1; break; } } } // 拼接行数据 $row .= '<tr>'; $row .= '<td>'.$match_id.'</td>'; $row .= '<td>'.$p1['player'].'</td>'; $row .= '<td>'.$p1['points'].'</td>'; if($match_p2 != null){ $row .= '<td>'.$match_p2['player'].'</td>'; $row .= '<td>'.$match_p2['points'].'</td>'; }else{ $row .= '<td>match not found</td>'; $row .= '<td>match not found</td>'; } $row .= '</tr>'; $match_id++; $visited[$i] = 1; } echo json_encode($row); }
后端Model部分(原有逻辑无需修改,保持获取全量玩家即可)
function playerss(){ $query = $this->db->get('player'); return $query->result(); }
逻辑说明
- 用visited数组标记已完成匹配的玩家,避免出现A匹配B、B又匹配A的重复记录
- 严格按照优先级匹配:先匹配同积分玩家,再匹配积分差≤10的玩家
- 奇数个玩家的场景下,最后一个没有匹配对象的玩家会自动标记
match not found
内容的提问来源于stack exchange,提问作者Ulquiorra Schiffer
相关产品推荐
相关产品推荐

