2016-09-10 2 views
0

Hier ist die CSV-Tabelle:Wie sortiert man CSV-Tabellendaten in PHP nach einer bestimmten Spalte?

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

nun mit streng PHP, ist es überhaupt zu sortieren nur die „Favoriten“ im Auftrag von „Alter“ aufsteigend? Eine erwartete Ausgabe wird in etwa so aussehen:

25 Grape 
30 Apple 
40 Orange 

Ich habe fgetcsv benutze sich auf das Dokument Echo, aber sie sind nicht nicht aufsteigend Alter sortiert, natürlich. Gibt es diese irgendwie in ein Array oder etwas zu sortieren, sortieren nach Alter und dann echo?

+2

@PaulCrovella nein, weil er speziell über die CSV-Array Konvertierung als auch fragen – NoobishPro

Antwort

1

Um Ihre CSV-Datei zu öffnen:

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 

Dann Sie array_multisort() verwenden könnte es auf einen Wert zu sortieren.

<?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

Sie auch die Datei wie folgt lesen: $ csv = array_map ('str_getcsv', Datei ('data.csv')) ; – Michel

+1

@Michel Sie sind nicht falsch, aber array_map ist erheblich langsamer als eine foreach. Nicht nur um ein bisschen, sondern um eine Menge. Durch den Austausch von Funktionen wie diesen (native PHP-Array-Funktionen sind extrem langsam) habe ich es geschafft, ein Skript von 3 Minuten auf 3 Sekunden herunterzufahren. siehe http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function für weitere Informationen – NoobishPro

+0

Sehr interessante Lektüre, danke. Mir ist aufgefallen, dass seit PHP7 array_map eigentlich um fast nichts schneller ist. – Michel

Verwandte Themen