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');
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 回答
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 回答