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

Aar*_*ron 1 php csv sorting

这是 CSV 表:

-------------------------
| Name | Age | Favorite |
-------------------------
| John | 30  | Apple    |
-------------------------
| Bill | 25  | Grape    |
-------------------------
| Ann  | 40  | Orange   |
-------------------------
Run Code Online (Sandbox Code Playgroud)

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

25 Grape
30 Apple
40 Orange
Run Code Online (Sandbox Code Playgroud)

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

Noo*_*Pro 5

要打开 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
Run Code Online (Sandbox Code Playgroud)

然后您可以使用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);
?>
Run Code Online (Sandbox Code Playgroud)