Skip to content
Advertisement

How to output random data from CSV in php?

I have a CSV file with 100 rows but want to output 5 of them at random like $data[0][1][2][3] and $data[2][2][3]

I got it to show but it shows in a group

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

Would like it to look like:

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

Advertisement

Answer

If you load the file into an array, it’s easy enough to come up with a list of “random” numbers, pull the corresponding line out, and use str_getcsv the same way you used fgetcsv in your code. It isn’t the most efficient way to do it, as you need to read the whole file into memory. But it’s necessary to determine the number of lines before choosing your random number.

<?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";
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement