如何在PHP中对多维数组进行排序 [英] How do I Sort a Multidimensional Array in PHP

查看:73
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆