【问题标题】:How to select a random set of rows?如何选择一组随机的行?
【发布时间】:2012-09-21 14:49:05
【问题描述】:

如何随机选择一组行

重要的部分:

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

【问题讨论】:

标签: php wordpress


【解决方案1】:
<?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'];
}
?>

【讨论】:

  • 比我的回答好得多,min 位很棒。
  • @SeanBright 谢谢,看起来它非常接近工作。有几次它选择了同一行……有一次它甚至选择了同一行 3 次。
  • 您是否有多行具有相同的sub_field_name
  • @SeanBright 是的,我知道,没有办法改变它,因为它是从 Wordpress 中获取的。
  • 我添加了一个我认为更好的不同实现。我还更正了原始实现。
【解决方案2】:

只需在随机行过程中循环您想要获取的随机行数。

<?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++;
}
?>

【讨论】:

    【解决方案3】:

    你可以试试这个

    $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 ;
    }
    

    【讨论】:

      【解决方案4】:

      一个简单的解决方案:

      $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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        • 2013-04-09
        • 1970-01-01
        相关资源
        最近更新 更多