This question already has an answer here:
- How can I sort arrays and data in PHP? 9 answers
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.
I know it's 2 years since this question was asked and answered, but here's another function that sorts a two-dimensional array. It accepts a variable number of arguments, allowing you to pass in more than one key (ie column name) to sort by. PHP 5.3 required.
Try it here: http://www.exorithm.com/algorithm/view/sort_multi_array
You can use array_multisort()
Try something like this:
For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:
With usort. Here's a generic solution, that you can use for different columns:
To sort by first column:
Multiple row sorting using a closure
Here's another approach using uasort() and an anonymous callback function (closure). I've used that function regularly. PHP 5.3 required – no more dependencies!
The "Usort" function is your answer.
http://php.net/usort