#native_company# #native_desc#

Sortable Table Using CSV Files

By Sally Evans
on November 19, 2004

Version: 2

Type: Sample Code (HOWTO)

Category: Databases

License: GNU General Public License

Description: This table will read data from a csv file and create a sortable table.

By clicking on the heading the table will be sort/reverse sort

echo "QUERY_STRING is ".$_SERVER['QUERY_STRING']."<p>"; 
if(isset($_GET['sortby']))$sortby = $_GET['sortby']; 
if(isset($_GET['rev']))$rev = $_GET['rev'];

//Open and read CSV file example has four columns
$ff=fopen('DataFile.csv','r') or die("Can't open file");

//Make columns sortable for each sortable column
foreach ($Data as $key => $row) {
   $One[$key]  = $row[0]; // could be $row['Colname']
   $Two[$key] = $row[1]; //numeric example
   $Three[$key] = $row[2];
   $Four[$key] = $row[3];} //numeric example
 //Case Statements for Sorting
   switch ($sortby){
   case "0":
   if($rev=="1")array_multisort($One, SORT_NUMERIC, $Data); //SORT_NUMERIC optional
   else array_multisort($One, SORT_NUMERIC, SORT_DESC,$Data);
   case "1":
   if($rev=="1")array_multisort($Two,  $Data);
   else array_multisort($Two, SORT_DESC, $Data);
   case "2":
   if($rev=="1")array_multisort($Three, SORT_NUMERIC, $Data);
   else array_multisort($Three, SORT_NUMERIC, SORT_DESC,$Data);
   case "3":
   if($rev=="1")array_multisort($Four,   $Data);
   else array_multisort($Four,  SORT_DESC, $Data);

echo ("<table border=2>");    //$rev is reverse variable	
echo ("<th><a href="SortTable.php?sortby=0&rev=$rev" title="Click to Sort/Reverse sort">One</a></th>");
echo ("<th><a href="SortTable.php?sortby=1&rev=$rev" title="Click to Sort/Reverse sort">Two</a></th>");
echo ("<th><a href="SortTable.php?sortby=2&rev=$rev" title="Click to Sort/Reverse sort">Three</a></th>");
echo ("<th><a href="SortTable.php?sortby=3&rev=$rev" title="Click to Sort/Reverse sort">Four</a></th>");

foreach($Data as $NewDat){
if($NewDat[0]!=""){ //error trap
foreach($NewDat as $field)$str.="<td>$field</td>";
echo $str;}}
echo "</table>";
// 19-11-04 www.sallyje.co.uk
//DataFile can be found here http://www.sallyje.co.uk/SortTable.php