I have a CSV file that has (dummy) data like this:
Mike Judge, Office Space, Comedy
Larry Wachowski, Matrix Zero, Action
Sofia Coppola, Lost In Translation, Drama
Ron Howard, A Beautiful Mind, Drama
Joe Biden, Your Big Hat, Sports
Barack Obama, The Stubborn Goat, Drama
Steve Smith, 2 Beautiful Ants, Suspense
Jared Hess, Napoleon Dynamite, Comedy
Jack Daniels, Field of Dreams, Drama
I need the 1st field sorted alphabetically by last name. That works.
Then I need to show the array in an HTML table and be able to set the number of columns to perhaps 5. I need each cell to hold one line from the CSV file, then move left to right filling the table.
Everything I've tried gets me almost there, but the table does not display properly - it has missing td tag or no in the last td.
Any help would be appreciated.
Here's what I have so far:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
echo '<table border="1" align="center"><tr>' . "\n";
foreach( $rows as $rows2 )
{
if ($i % $numCols == 0 && $i != 0)
echo "</tr>\n<tr>"; // every time but the first
echo '<td>';
foreach( $rows2 as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
}
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
