2011-12-20 8 views
8

Mam problem z odczytaniem pliku rozdzielanego tabulatorami.Jak utworzyć tablicę strukturalną z pliku Tabdelimited z PHP?

Struktura na moim pliku jest:

Field 1  Field 2  Field 3 
Element11 Element12 Element13 
Element21 Element22 Element23 
Element31 Element32 Element33 

Od tego pliku Chcę utworzyć tablicę z tej struktury:

$csv = array(
      array( 'Field 1' => 'Element11', 
        'Field 2' => 'Element12', 
        'Field 3' => 'Element13', 

      ), 
      array( 'Field 1' => 'Element21', 
        'Field 2' => 'Element22', 
        'Field 3' => 'Element23', 

      ), 
      array( 'Field 1' => 'Element31', 
        'Field 2' => 'Element32', 
        'Field 3' => 'Element33', 

      )  
     ); 

Jak mogę to zrobić?

Odpowiedz

17

Aby uzyskać także nagłówki jako klucze tablicy trzeba

$result = array(); 
$fp = fopen('/path/to/file','r'); 
if (($headers = fgetcsv($fp, 0, "\t")) !== FALSE) 
    if ($headers) 
    while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) 
     if ($line) 
     if (sizeof($line)==sizeof($headers)) 
      $result[] = array_combine($headers,$line); 
fclose($fp); 
print_r($result); 
1

fgetcsv():

$result = array(); 
$fp = fopen('/path/to/file','r'); 
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) $result[] = $line; 
fclose($fp); 

print_r($result); 

Jeśli chcesz pominąć ten wiersz nagłówka, po prostu zadzwoń fgets() raz przed wejściem do pętli. Lub jeśli chcesz być tablicę asocjacyjną jak przedstawiono powyżej:

$result = array(); 
$fp = fopen('/path/to/file','r'); 
$headers = fgetcsv($fp, 0, "\t"); 
$row = 0; 
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) { 
    for ($col = 0; isset($line[$col]); $col++) { 
    $result[$row][$header[$col]] = $line[$col]; 
    } 
    $row++; 
} 
fclose($fp); 

print_r($result); 
+0

Faktycznie, plik nie jest [C] OMMA [S] eperated (CSV) :) – tim

+2

CSV stał się synonimem dla ... no cóż, "dane oddzielone przez coś", i jako kolega współpracownik z powrotem w czasach używanych do powiedzenia; "Wartości rozdzielone znakami" –

+0

@ColHeather Dlatego podałem '" \ t "' jako trzeci parametr do 'fgetcsv()' ... :-D – DaveRandom

Powiązane problemy