简体   繁体   English

如何从我的第一个数组中获取随机用户名但检查第二个数组

[英]How can I get a random username from my first array but check the second array

How can I get a random username from my first array, but the username selected shouldn't be in the "denied usernames Array" in PHP如何从我的第一个数组中获取随机用户名,但选择的用户名不应该在 PHP 的“拒绝用户名数组”中

Array of usernames
Array ( 
  [0] => stdClass Object ( [user_login] => emma88 ) 
  [1] => stdClass Object ( [user_login] => milli ) 
  [2] => stdClass Object ( [user_login] => publishers@a.com ) 
  [3] => stdClass Object ( [user_login] => shawn ) 
  [4] => stdClass Object ( [user_login] => shawnfao2 ) 
) 
2021-03-23
2021-03-23

denied usernames Array: 
Array ( 
   [0] => Array ( [username] => emma88 ) 
   [1] => Array ( [username] => milli ) 
   [2] => Array ( [username] => publishers@a.com ) 
)

Have a look at array_filter :看看array_filter

Filters elements of an array using a callback function使用回调 function 过滤数组元素

Using an appropriate callback, you can create a list of users which are not in the denied list, eg使用适当的回调,您可以创建不在拒绝列表中的用户列表,例如

$filteredUsers = array_filter($users, function($item) use ($denyList) {
    return ! in_array($item->user_login, $denyList);
}

You can use array_column to simplify the deny list array first.您可以先使用array_column来简化拒绝列表数组。

You can then use array_rand or shuffle to pick one at random.然后,您可以使用array_randshuffle 随机选择一个。

  1. For both $valid and $invalid users;对于$valid$invalid用户;

  2. Use array_diff to get all the users that are in $validusers , but not in $invalidusers使用array_diff获取$validusers中的所有用户,但不是$invalidusers

  3. Use array_rand to get a single index of the newly array使用array_rand获取新数组的单个索引

<?php

    $valid = [ (Object) ['user_login' => 'emma88'], (Object) ['user_login' => 'milli'], (Object) ['user_login' => 'shawn'] ]; 
    $invalid = [ (Object) ['user_login' => 'emma88'] ]; 

    $validusers = array_column($valid, 'user_login');
    $invalidusers = array_column($invalid, 'user_login');

    $onlyvalidusers = array_diff($validusers, $invalidusers);

    $randIndex = array_rand($onlyvalidusers, 1);
    var_dump($onlyvalidusers[$randIndex]);

Try it online! 在线尝试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM