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?

6

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect thank you just the answer I was looking for!
how would I add other values from the same column as the year like "make" ?
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 - php.net/manual/en/array.sorting.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.