2013-03-12 32 views
2

我想找出一種方法來選擇一定比例的特定數組項目。因此,讓我們說:PHP選擇數組項目時間百分比?

$testArray = array('item1', 'item2', 'item3', 'item4', 'item5'); 

現在我會怎麼去讓item1選擇讓40%的時間。我知道這可能很容易,但我今天似乎無法將其包圍。

回答

3

隨着這些百分比:

$chances = array(40,15,15,15,15); 

選擇1和100之間的隨機數:

$rand = rand(1,100); 

而選擇根據數組項:

| item1    | item2 | item3 | item4 | item5 | 
0     40  55  70  85  100 
$ref = 0; 
foreach ($chances as $key => $chance) { 
    $ref += $chance; 
    if ($rand <= $ref) { 
     return $testArray[$key]; 
    } 
} 

POSS對於更一般的溶液IBLE改進:

  • 使用array_sum()代替100
  • 確保$chances具有相同的鍵作爲輸入數組(即與array_keysarray_combine
+0

+1對於好的和簡單的邏輯 – 2013-03-12 07:46:01