Forum Moderators: coopster
<?php
$filename = 'someCsvFile.csv';
$how_many_to_show = 4;
$csv = @fopen($filename, 'r');
if ($csv) {
$csvData =array();
$csvHeadings = fgetcsv($csv, 4000); //assuming the first line of the csv file contains the headings
if (!$csvHeadings) {
die('Unable to parse csv file headings!');
}
$numHeadings = count($csvHeadings);
while (!feof($csv)) { //read the csv file into our $csvData array
$tmp = fgetcsv($csv, 4000);
if ($tmp) {
array_push($csvData, $tmp);
}
}
shuffle($csvData); //randomize the order of $csvData items
for ($i = 0; $i < $how_many_to_show; $i++) {
if (count($csvData[$i]) == $numHeadings) { //array_combine() requires both arrays to be same length
$csvItem = array_combine($csvHeadings, $csvData[$i]);
//$csvHeadings items become keys in $csvItem, $csvData[$i] items become the values in $csvItem
$s = '<h3>$csvItem '.$i."</h3>\r\n<p>";
foreach ($csvItem as $key => $value) { //now you have access to the keys (heading names) if desired
$s .= $key.' => '.$value."<br>\r\n";
}
echo preg_replace('/<br>\\r\\n$/', "\r\n</p>\r\n", $s);
}
}
} else {
die('Could not get contents of: ' . $filename);
}
?>
my CSV file which is delimited by a semi-colon
//read the csv file into our $csvData array
//read the REST of the csv file into our $csvData array
.....
shuffle($csvData); //randomize the order of $csvData items
$resultsFile = fopen('randomResults.csv', 'w'); //will write the results to this file
for ($i = 0; $i < $how_many_to_show; $i++) {
fputcsv($resultsFile, $csvData[$i], ';'); //write the current array from $csvData into $resultsFile as csv fields
if (count($csvData[$i]) == $numHeadings) { //array_combine requires both arrays to be same length
$csvItem = array_combine($csvHeadings, $csvData[$i]);
//$csvHeadings items become keys in $csvItem, $csvData[$i] items become the values in $csvItem
$s = '<h3>$csvItem '.$i."</h3>\r\n<p>";
foreach ($csvItem as $key => $value) { //now you have access to the keys (heading names) if desired
$s .= $key.' => '.$value."<br>\r\n";
}
echo preg_replace('/<br>\\r\\n$/', "\r\n</p>\r\n", $s);
}
}
fclose($resultsFile);
} else {
.....