如何按特定列对PHP中的CSV表数据进行排序?

时间:2016-09-10 01:14:21

标签: php sorting csv

这是CSV表:

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

现在,严格使用PHP,无论如何只按“年龄”的升序排序“收藏夹”?预期的输出将是这样的:

25 Grape
30 Apple
40 Orange

我一直在使用fgetcsv将它们回显到文档中,但当然,它们并没有按升序年龄排序。无论如何将它们放在一个数组或其他东西中,按年龄排序,然后回声?

1 个答案:

答案 0 :(得分:3)

要打开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);
?>