簡體   English   中英

如何選擇一組隨機行?

[英]How to select a random set of rows?

如何選擇一組隨機行

重要的一點:

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

只需循環遍歷隨機行處理您想要獲得的隨機行數。

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

你可以嘗試一下

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

簡單的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM