0

I have this array called $csv, it contains cars that have year, make and model.

function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
    $line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}


// Set path to CSV file
$csvFile = 'csv/file.csv';
$csv = readCSV($csvFile);
array_shift($csv); 

foreach($csv as $car){

$year = $car[3];
$make = $car[4];
$model = $car[5];

echo $year;
}

This gives me - 2011 2009 2012 2012 2013

How would I filter the results to display in order by newest to oldest?

Ryan D
  • 741
  • 1
  • 11
  • 29
  • 1
    didn't you post something related earlier? http://stackoverflow.com/questions/35108849/how-do-i-sort-and-organize-data-from-csv-file-in-php – Funk Forty Niner Jan 31 '16 at 02:09
  • Earlier I wanted to get the count for inventory based on how long I have had each car. This is for displaying the inventory itself in a feed. It displays now but I want to know how to filter the results. – Ryan D Jan 31 '16 at 02:12
  • Have a look at the many sorting functions that PHP has to offer http://php.net/manual/en/array.sorting.php - http://php.net/manual/en/function.sort.php – Funk Forty Niner Jan 31 '16 at 02:14
  • then these Q&A's http://stackoverflow.com/q/1272494/ - http://stackoverflow.com/q/11649840/ – Funk Forty Niner Jan 31 '16 at 02:16
  • Possible duplicate of [PHP Sort Array by date value](http://stackoverflow.com/questions/15557373/php-sort-array-by-date-value) – Dan Ovidiu Boncut Jan 31 '16 at 03:01
  • or [this](http://stackoverflow.com/questions/11649840/multidimensional-array-sorting-procedure-for-csv-files?lq=1) one for multidimensional arrays –  Jan 31 '16 at 03:19

1 Answers1

1
$years = [];
foreach($csv as $car){
    $years[] = $car[3];
}

rsort($years);

foreach($years as $year) {
    echo $year;
}

If you need low-to-high sorting use sort instead of rsort.

Ajk_P
  • 1,874
  • 18
  • 23
  • Perfect thank you just the answer I was looking for! – Ryan D Jan 31 '16 at 03:21
  • how would I add other values from the same column as the year like "make" ? – Ryan D Jan 31 '16 at 04:13
  • do you want to keep them sorted by year too? If so you have a few options: 1. create an array with year as keys, and other data on values and sort on the keys. 2. (Best IMO). Simply create a sort function. If you don't care about the original array $csv, you could directly sort that based on the third column. Take a look at this - http://php.net/manual/en/array.sorting.php – Ajk_P Feb 01 '16 at 19:22