【问题标题】:How to output random data from CSV in php?如何在 php 中从 CSV 输出随机数据?
【发布时间】:2019-04-22 20:48:06
【问题描述】:

我有一个包含 100 行的 CSV 文件,但想随机输出其中的 5 个,例如 $data[0][1][2][3] 和 $data[2][2][3]

我让它显示,但它显示在一个组中

<?php 
 $row = 1;
 if (($handle = fopen("Book1.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);

       $row++;
       for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
       }
      }
   fclose($handle);
 }
?>

希望它看起来像:

some data:<?php echo $data[0][1][2][3];?>
more data:<?php echo $data[1][1][2][3];?>
more data:<?php echo $data[5][1][2][3];?>
more data:<?php echo $data[8][1][2][3];?>

【问题讨论】:

    标签: php arrays csv


    【解决方案1】:

    如果您是load the file into an array,则很容易得出"random" numbers 的列表,拉出相应的行,然后像在代码中使用fgetcsv 一样使用str_getcsv。这不是最有效的方法,因为您需要将整个文件读入内存。但有必要在选择随机数之前确定行数。

    <?php 
    $rows = file("Book1.csv");
    $len = count($rows);
    $rand = [];
    while (count($rand) < 5) {
        $r = rand(0, $len);
        if (!in_array($r, $rand)) {
            $rand[] = $r;
        }
    }
    foreach ($rand as $r) {
        $csv = $rows[$r];
        $data = str_getcsv($csv);
        // now do whatever you want with $data, which is one random row of your CSV
        echo "first column from row $r: $data[0]\n";
    }
    

    【讨论】:

    • 谢谢,它可以工作,但是如果我想单独输出每个元素而不是联合输出呢
    • 我没有关注。你有一个数组中每一行的数据,你可以用它做任何你想做的事情。
    猜你喜欢
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多