在PHP中从CSV输出随机数据

时间:2019-04-22 20:48:06

标签: php arrays csv

我有一个包含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];?>

1 个答案:

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