0

行のランダムなセットを選択するにはどうすればよいですか

重要なビット:

  1. 変数を介して選択するランダム行の数を指定する必要があります。
  2. たとえば、選択したい行数が 10 の場合、10の異なるを選択する必要があります。10になるまで同じ行を数回選択したくありません。

以下のコードは 1 つのランダムな行を選択します。これを上記の仕様に合わせるにはどうすればよいですか?

<?php $rows = get_field('repeater_field_name');
$row_count = count($rows);
$i = rand(0, $row_count - 1);

echo $rows[$i]['sub_field_name']; ?>
4

4 に答える 4

2
<?php
    $rows = get_field('repeater_field_name');
    $row_count = count($rows);
    $rand_rows = array();

    for ($i = 0; $i < min($row_count, 10); $i++) {
        // Find an index we haven't used already (FYI - this will not scale
        // well for large $row_count...)
        $r = rand(0, $row_count - 1);
        while (array_search($r, $rand_rows) !== false) {
            $r = rand(0, $row_count - 1);
        }
        $rand_rows[] = $r;

        echo $rows[$r]['sub_field_name'];
    }
?>

これはより良い実装です:

<?
$rows_i_want = 10;
$rows = get_field('repeater_field_name');

// Pull out 10 random rows
$rand = array_rand($rows, min(count($rows), $rows_i_want));

// Shuffle the array
shuffle($rand);                                                                                                                     

foreach ($rand as $row) {
    echo $rows[$row]['sub_field_name'];
}
?>
于 2012-09-21T14:54:15.617 に答える
0

取得したいランダム行の数だけランダム行プロセスをループするだけです。

<?php
$rows_to_get=10;
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$x=0
while($x<$rows_to_get){
    echo $rows[rand(0, $row_count - 1)]['sub_field_name'];
    $x++;
}
?>
于 2012-09-21T14:53:50.947 に答える
0

簡単な解決策:

$rows = get_field('repeater_field_name');
$limit = 10;

// build new array
$data = array();
foreach ($rows as $r) { $data[] = $r['sub_field_name']; }
shuffle($data);
$data = array_slice($data, 0, min(count($data), $limit));

foreach ($data as $val) {
  // do what you want
  echo $val;
}
于 2012-09-21T15:25:13.740 に答える
0

あなたはこれを試すことができます

$rows = get_field('repeater_field_name');
var_dump(__myRand($rows, 10));

function __myRand($rows, $total = 1) {
    $rowCount = count($rows);
    $output = array();
    $x = 0;
    $i = mt_rand(0, $rowCount - 1);

    while ( $x < $total ) {
        if (array_key_exists($i, $output)) {
            $i = mt_rand(0, $rowCount - 1);
        } else {
            $output[$i] = $rows[$i]['sub_field_name'];
            $x ++;
        }
    }
    return $output ;
}
于 2012-09-21T15:00:28.280 に答える