2016-09-10 56 views
0

這裏的CSV表:如何在PHP中按特定列對CSV表格數據進行排序?

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

現在,使用PHP嚴格,反正是有那種只有「收藏」由升的「年齡」的命令?預期產出將是這樣的:

25 Grape 
30 Apple 
40 Orange 

我一直在使用fgetcsv他們呼應到文檔,但他們不是不按升序年齡,病程的排序。無論如何要將它們放入數組或其他東西,按年齡分類,然後回顯?

+2

@PaulCrovella沒有,因爲他專門詢問有關CSV數組轉換以及 – NoobishPro

回答

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); 
?> 
+0

你也可以讀出這樣的文件:$ CSV = array_map(「str_getcsv」,文件(「data.csv」)) ; – Michel

+1

@Michel你沒有錯,但是array_map比foreach慢得多。不只是一點點,而是一個很大的。通過替換這些函數(原生php陣列函數非常緩慢),我設法將腳本從3分鐘縮短到3秒。請參閱http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function獲取更多信息 – NoobishPro

+0

非常有趣的閱讀,謝謝。我注意到,由於PHP7 array_map實際上更快速。 – Michel

相關問題