簡體   English   中英

如何獲得具有值的隨機關聯數組鍵

[英]How to get random associative array key having value in bounds

假設我有這個

$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()循環要慢,但是除非您不處理大量數據,否則差異可以忽略不計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM