dongluanguang4774 2008-09-18 20:45
浏览 157
已采纳

如何在PHP中对多维数组进行排序[重复]

This question already has an answer here:

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.

</div>
  • 写回答

11条回答 默认 最新

  • dongzhi2332 2008-09-18 20:57
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型