Created
January 5, 2016 02:03
-
-
Save shnr/ef908d38a2b7b4a55d1d to your computer and use it in GitHub Desktop.
配列を優先度順に表示 ref: http://qiita.com/shbr216/items/0e159e46d7262bed91a9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 確率を持つ要素を用意 | |
$arr = array( | |
array( | |
"val" => "90%の優先度", | |
"per" => 90 | |
), | |
array( | |
"val" => "70%の優先度", | |
"per" => 70 | |
), | |
array( | |
"val" => "50%の優先度", | |
"per" => 50 | |
), | |
array( | |
"val" => "30%の優先度", | |
"per" => 30 | |
), | |
array( | |
"val" => "10%の優先度", | |
"per" => 10 | |
) | |
); | |
// rand()で使う最大値を用意 | |
$max = 0; | |
foreach ($arr as $key => $value) { | |
$max += $value['per']; | |
} | |
$len = count($arr); | |
for ($i=0; $i < $len; $i++) { | |
// 指定範囲からランダムにターゲットとなる数値を取得 | |
$tar = rand(1, $max); | |
foreach ($arr as $key => $value) { | |
if($tar <= $value['per']){ | |
// 優先度が数値より高ければ表示。 | |
echo '<li>'. $value['val'] . '</li>'; | |
// 要素を配列から削除 | |
unset($arr[$key]); | |
// 最大値を再調整 | |
$max -= $value['per']; | |
break; | |
}else{ | |
// ターゲットとなる数値を調整 | |
$tar -= $value['per']; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment