如何获取在边界中具有值的随机关联数组键



假设我有这个

$users = array("usr-123"=>-7,"usr-183"=>0,"usr-12"=>2,"usr-43"=>3,"usr-67"=>3);
$startVal = 0; 
$endVal = 3;

$usrSelected = array_intersect($users, range($startVal, $endVal));

会给我一个新数组,其中包含范围内的所有项目 (0..3(

Array
(
    [usr-183] => 0
    [usr-12] => 2
    [usr-43] => 3
    [usr-67] => 3
)

而这个

$usrSelected = array_rand(array_intersect($users, range($startVal, $endVal)));

会给我一个来自上一个数组的随机密钥......

我将如何从这个具有$startVal、$endVal范围内的关联数组中获得一个gmt_offset的随机键?

$users = array (
    'usr-123' => array('cid' => 'US', 'country' => 'Usa', "timezone"=>'America/Los_Angeles', "gmt_offset"=> -7),
    'usr-183' => array('cid' => 'EC', 'country' => 'Ecuador', "timezone"=>'America/Guayaquil', "gmt_offset"=> -5),
    'usr-12' => array('cid' => 'BO', 'country' => 'Bolivia', "timezone"=>'America/La_Paz', "gmt_offset"=> -4),
    'usr-43' => array('cid' => 'UY', 'country' => 'Uruguay', "timezone"=>'America/Montevideo', "gmt_offset"=> -3),
    'usr-67' => array('cid' => 'GB', 'country' => 'United Kingdom', "timezone"=>'Europe/London', "gmt_offset"=> 0),
    'usr-3' => array('cid' => 'FR', 'country' => 'France', "timezone"=>'Europe/Paris', "gmt_offset"=> 1),
    'usr-256' => array('cid' => 'ES', 'country' => 'Spain', "timezone"=>'Europe/Madrid', "gmt_offset"=> 1),
    'usr-453' => array('cid' => 'DE', 'country' => 'Germany', "timezone"=>'Europe/Berlin', "gmt_offset"=> 1),
    'usr-534' => array('cid' => 'GR', 'country' => 'Greece', "timezone"=>'Europe/Athens', "gmt_offset"=> 2),
    'usr-452' => array('cid' => 'RU', 'country' => 'Russian Federation', "timezone"=>'Europe/Kaliningrad', "gmt_offset"=> 2),
    'usr-545' => array('cid' => 'RU', 'country' => 'Russian Federation', "timezone"=>'Europe/Moscow', "gmt_offset"=> 3),
    'usr-74' => array('cid' => 'RO', 'country' => 'Romania', "timezone"=>'Europe/Bucharest', "gmt_offset"=> 3),
    'usr-2345' => array('cid' => 'PK', 'country' => 'Pakistan', "timezone"=>'Asia/Karachi', "gmt_offset"=> 5),
    'usr-45' => array('cid' => 'CN', 'country' => 'China', "timezone"=>'Asia/Shanghai', "gmt_offset"=> 8),
    'usr-19' => array('cid' => 'NZ', 'country' => 'New Zealand', "timezone"=>'Pacific/Auckland', "gmt_offset"=> 12),
);

任何帮助都将不胜感激。

您正在寻找类似以下内容:

$startVal = 0;
$endVal = 3;
$random = array_rand(array_filter($users, function($v) use ($startVal, $endVal) {
    return $v['gmt_offset'] >= $startVal && $v['gmt_offset'] <= $endVal;
}));

https://eval.in/799748

注意:这可能比常规的foreach((循环慢,但除非你不处理大量的数据,否则差异可以忽略不计。

最新更新