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);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?