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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?