1

Here's the CSV table:

-------------------------
| Name | Age | Favorite |
-------------------------
| John | 30  | Apple    |
-------------------------
| Bill | 25  | Grape    |
-------------------------
| Ann  | 40  | Orange   |
-------------------------

Now, using strictly PHP, is there anyway to sort only the "Favorite" by ascending order of "Age"? An expected output would be something like this:

25 Grape
30 Apple
40 Orange

I've been using fgetcsv to echo them onto the document, but they are not not sorted by ascending age, of course. Is there anyway to throw these in an array or something, sort by age, and then echo?

Aaron
  • 531
  • 3
  • 8
  • 22

1 Answers1

5

To open up your CSV file:

function readCSV($file)
{
  $row      = 0;
  $csvArray = array();
  if( ( $handle = fopen($file, "r") ) !== FALSE ) {
    while( ( $data = fgetcsv($handle, 0, ";") ) !== FALSE ) {
      $num = count($data);
      for( $c = 0; $c < $num; $c++ ) {
        $csvArray[$row][] = $data[$c];
      }
      $row++;
    }
  }
  if( !empty( $csvArray ) ) {
    return array_splice($csvArray, 1); //cut off the first row (names of the fields)
  } else {
    return false;
  }
}

$csvData = readCSV($csvPath); //This is your array with the data

Then you could use array_multisort() to sort it on a value.

<?php
// Obtain a list of columns
foreach ($csvData as $key => $row) {
    $age[$key]  = $row['volume'];
    $favorite[$key] = $row['edition'];
}

// Sort the data with age first, then favorite
// Add $csvData as the last parameter, to sort by the common key
array_multisort($age, SORT_ASC, $favorite, SORT_ASC, $csvData);
?>
NoobishPro
  • 2,539
  • 1
  • 12
  • 23
  • you could also read the file like this: $csv = array_map('str_getcsv', file('data.csv')); – Michel Sep 10 '16 at 02:05
  • 1
    @Michel you're not wrong, but array_map is considerably slower than a foreach. Not just by a little, but by a LOT. By replacing functions such as those (native php array functions are extremely slow) I managed to get a script down from 3 minutes to 3 seconds. see http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function for more information – NoobishPro Sep 10 '16 at 02:14
  • Very interesting reading, thanks. I noticed that since PHP7 array_map is actually faster by next to nothing. – Michel Sep 10 '16 at 02:22