【问题标题】:How to sort CSV table data in PHP by a specific column?如何按特定列对 PHP 中的 CSV 表数据进行排序?
【发布时间】:2016-09-10 09:39:21
【问题描述】:

这是 CSV 表:

-------------------------
| Name | Age | Favorite |
-------------------------
| John | 30  | Apple    |
-------------------------
| Bill | 25  | Grape    |
-------------------------
| Ann  | 40  | Orange   |
-------------------------

现在,严格使用 PHP,是否可以按“年龄”的升序仅对“收藏夹”进行排序?预期的输出是这样的:

25 Grape
30 Apple
40 Orange

我一直在使用fgetcsv 将它们回显到文档中,但它们当然不是按年龄升序排序的。有没有办法将这些放入数组或其他东西中,按年龄排序,然后回显?

【问题讨论】:

  • @PaulCrovella 不,因为他也在专门询问 CSV 到数组的转换

标签: php sorting csv


【解决方案1】:

打开 CSV 文件:

function readCSV($file)
{
  $row      = 0;
  $csvArray = array();
  if( ( $handle = fopen($file, "r") ) !== FALSE ) {
    while( ( $data = fgetcsv($handle, 0, ";") ) !== FALSE ) {
      $num = count($data);
      for( $c = 0; $c < $num; $c++ ) {
        $csvArray[$row][] = $data[$c];
      }
      $row++;
    }
  }
  if( !empty( $csvArray ) ) {
    return array_splice($csvArray, 1); //cut off the first row (names of the fields)
  } else {
    return false;
  }
}

$csvData = readCSV($csvPath); //This is your array with the data

然后您可以使用array_multisort() 对其进行排序。

<?php
// Obtain a list of columns
foreach ($csvData as $key => $row) {
    $age[$key]  = $row['volume'];
    $favorite[$key] = $row['edition'];
}

// Sort the data with age first, then favorite
// Add $csvData as the last parameter, to sort by the common key
array_multisort($age, SORT_ASC, $favorite, SORT_ASC, $csvData);
?>

【讨论】:

  • 你也可以这样读取文件:$csv = array_map('str_getcsv', file('data.csv'));
  • @Michel 你没有错,但是 array_map 比 foreach 慢得多。不只是一点点,而是很多。通过替换诸如那些(原生 php 数组函数非常慢)之类的函数,我设法将脚本从 3 分钟缩短到 3 秒。请参阅stackoverflow.com/questions/18144782/… 了解更多信息
  • 非常有趣的阅读,谢谢。我注意到,由于 PHP7 array_map 实际上几乎没有更快。
猜你喜欢
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多