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

时间:2017-05-18 07:03:10

标签: php

我们说我有这个

$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),
);

任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

你正在寻找这样的事情:

$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()循环慢,但除非您不处理大量数据,否则差异可以忽略不计。