8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列を優先度順に表示

Posted at

要素をランダムに一覧表示、かつそれぞれに優先度を持たせたい場合。
これでどうだろうか?

Code

code

kobito.php

<?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'];
        }
     }

  }


8
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?