如何在 PHP 中对多维数组进行排序 [英] How do I Sort a Multidimensional Array in PHP
问题描述
我已将 CSV 数据加载到多维数组中.通过这种方式,每个行"都是一条记录,每个列"都包含相同类型的数据.我正在使用下面的函数来加载我的 CSV 文件.
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;
}
我需要能够指定一列进行排序,以便它重新排列行.其中一列包含 Y-m-d H:i:s
格式的日期信息,我希望能够以最近的日期作为第一行进行排序.
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.
推荐答案
您可以使用 array_multisort()
试试这样的:
foreach ($mdarray as $key => $row) {
// replace 0 with the field's index/key
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $mdarray);
对于 PHP >= 5.5.0 只需提取要排序的列.不需要循环:
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);
这篇关于如何在 PHP 中对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!