2017-05-18 27 views
0

比方说,我有这个如何获得在边界随机关联数组键具有价值

$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所有项目的新数组。 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这个关联有gmt_offset阵列,$ endVal范围?

$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

您正在寻找这样的事情:

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

+0

感谢您的回复marekpw。 我只是在我的数据上测试它,并且与大约60K的用户一起工作正常! 非常感谢! –