duandu2980 2015-01-21 01:56
浏览 27
已采纳

如何在数组中找到具有递增编号值的可用点?

Let's say I have an array of usernames as such:

[
'john.doe',
'john.doe1',
'john.doe2',
'john.doe4',
'john.doe5'
]

Now a new user registers as john.doe. I have fetched the already existing john.doe's from the DB using a LIKE query and stored in the array above. Then I want to iterate over that array to see which spot is available for the newly registered john.doe.

In this case the available spot would be john.doe3.

I know how to do this using a while loop and simply adding an increment until there's no match.

Basically I have two questions:

  • Is this the right way of approaching this duplicate username issue altogether?

  • I was wondering if maybe there's a better way in lieu of using the while loop?

  • 写回答

1条回答 默认 最新

  • douyin2962 2015-01-21 05:31
    关注
    1. Nope - better to use an identity token, consider adding a third value such as: md5('username'.'date') or md5('username'.'fullname') and then you can use this identifier for the specific user.

      The better practice will be to use only the user row id for relations and for any query and the only step you use the username ( + password) is at login.

    2. Here you go:

      //without while:
      /* NOT TESTED */
      /* $uname -> is the username requested without the duplicate number */
      function find_aspot($arr, $uname) {
          natsort($arr);
          if (empty($arr) || $arr[0] !== $uname) return $uname;
          foreach($arr as $key => $data) {
             $cur = str_replace($uname,'',$data);
             $cur = ($cur === '')?0:intval($cur);
             if (!isset($arr[$key+1])) break;
             $next = intval(str_replace($uname,'',$arr[$key+1]))
             if ($cur+1 !== $next) break;
          }
          return $uname.($cur+1);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在