Search code examples
phparrayssortingmultidimensional-array

Sort a 2D array by a column DESC


I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.

function f_parse_csv($file, $longest, $delimiter)
{
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter))
  {
    array_push($mdarray, $line);
  }
  fclose($file);
  return $mdarray;
}

I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of Y-m-d H:i:s and I would like to be able to sort with the most recent date being the first row.


Solution

  • You can use array_multisort()

    Try something like this:

    foreach ($mdarray as $key => $row) {
        // replace 0 with the field's index/key
        $dates[$key]  = $row[0];
    }
    
    array_multisort($dates, SORT_DESC, $mdarray);
    

    For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

    array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);