2011-12-20 38 views
8

我在閱讀製表符分隔文件時遇到問題。如何使用PHP從Tabdelimited文件創建結構化數組?

我的文件結構是:

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

從這個文件我想用這種結構創建磁盤陣列:

$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', 

      )  
     ); 

我怎樣才能做到這一點?

回答

17

也得到了標題爲數組鍵,你需要

$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); 

如果你想跳過標題行,只需撥打fgets()一旦進入循環之前。或者,如果你想要的數組是聯想爲上面所描繪的:

$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

事實上,該文件不是[C] OMMA [S] eperated(CSV):) – tim 2011-12-20 10:56:30

+2

CSV已經成爲...的代名詞,「數據被某種東西隔開」,並且在過去常說的日子裏成爲同事的同事。 「字符分隔值」 – 2011-12-20 10:58:21

+0

@ColHeather這就是爲什麼我提供了''\ t「'作爲'fgetcsv()'的第三個參數...... :-D – DaveRandom 2011-12-20 10:59:55