2017-04-10 52 views
0

我有以下CSV:將csv解析爲關聯數組php;分隔符

稱號;標題2; TITLE3
測試,文本,文本2
test1的; text1的;文字3

我想將其轉換爲關聯數組,如:

[0] 
title => test, 
title2 => text 
title3 => text2 
[1] 
title => test1, 
title2 => text1 
title3 => text3 

我試着用:

$array = $fields = array(); $i = 0; 
$handle = @fopen("file", "r"); 
if ($handle) { 
    while (($row = fgetcsv($handle, ";")) !== false) { 
     if (empty($fields)) { 
      $fields = $row; 
      continue; 
     } 
     foreach ($row as $k=>$value) { 
      $array[$i][$fields[$k]] = $value; 
     } 
     $i++; 
    } 
    if (!feof($handle)) { 
     echo "Error: unexpected fgets() fail\n"; 
    } 
    fclose($handle); 
} 

感謝

+0

什麼這個問題你代碼?它輸出的是什麼? – hassan

回答

1

第一,而不是使用fpoen,fgetcsv,FCLOSE你可以簡單地使用file功能,這是回報您的文件作爲一個數組,這情況下,如果你正在處理小文件,而不是一個大的csv文件,如果雖然這會更好地使用fopen。在黑暗

$csvFile = file('file.csv'); 

// 1 - get the first element of our array 
// 2 - shift it 
// 3 - parse it to an array using str_getcsv 
$keys = str_getcsv(array_shift($csvFile), ';'); 
foreach ($csvFile as $csvRecord) { 
    // combine our $csvRecord with $keys array 
    $csv[] = array_combine($keys, str_getcsv($csvRecord, ';')); 
} 

print_r($csv); 
0

射擊:

,那麼你可以按照如下結合起來(沒有測試過)

嘗試以下:

$array = $fields = array(); 
$first_array = array(); 
$i = 0; 
if (($handle = fopen("filename", "r")) !== FALSE) { 
    while (($data = fgetcsv($handle, ";")) !== FALSE) { 

     if (empty($data)) { 
      continue; 
     } 

     foreach ($data as $k=>$value) { 
      if($i==0) 
      { 
       $first_array[$k] = $value; 
      } 
      else if(!empty($first_array)) 
      { 
       $array[$i][$first_array[$k]] = $value; 
      } 
     } 
     $i++; 
    } 
    fclose($handle); 
}