如何选择一组随机行?

时间:2012-09-21 14:49:05

标签: php wordpress

如何选择一组随机行

重点:

  1. 我需要指定通过变量选择的随机行数。
  2. 例如,我想要选择的行数为10,然后 HAS TO 选择10个 DIFFERENT 行。我不希望它几次挑出同一行,直到它有10个。
  3. 下面的代码挑选出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 个答案:

答案 0 :(得分: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'];
}
?>

答案 1 :(得分: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++;
}
?>

答案 2 :(得分: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 ;
}

答案 3 :(得分: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;
}