2013-01-08 124 views
1

我的CSV文件具有這種結構CSV到PHP關聯數組

title;firstName;lastName;email; 
Sir;Bob;Public;[email protected]; 

第一行顯示的列名。內容從第二行開始。現在,我想這放入關聯數組這樣

array([0] => 
      array(
        'title' => 'Sir', 
        'firstName' => 'Bob', 
        'lastName' => 'Public', 
        'email' => '[email protected]' 
      ) 
) 

我試了一下:

$entities = array(); 

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { 

     $num = count($data); 

     for ($c = 0; $c < $num; $c++) { 

       $line = array(); 
       //save first row 
       if ($row == 1) { 
        foreach (explode(';', $data[$c]) as $field) { 
         //dont save empty fields 
         if ($field != "") { 
         $fields[] = $field; 
         $line[$field] = array(); 
         } 
        } 
       } 
       //go through contents and save them 
       foreach ($fields as $field) { 
        for ($i = 2; $i < count($fields); $i++) { 
         $cust = explode(";", $data[$c]); 
         $line[$field][] = $cust[$i]; 
        } 
       } 
       $entities[] = $line; 
       $row++; 
      } 
     } 

     fclose($handle); 
    } 

這給沒有錯誤,但是,這似乎是搞砸了一個怪陣。任何想法如何能得到我想要的結構?

+3

你有一個';'分隔的文件還沒有要指定的','作爲分隔符。 –

+0

謝謝,我編輯了我的問題 –

+0

[CSV到關聯數組]的可能重複(http://stackoverflow.com/questions/4801895/csv-to-associative-array) – ManseUK

回答

4

這應該工作:

$entities = array(); 
$header = fgetcsv($handle, 0, ";"); // save the header 
while (($values = fgetcsv($handle, 0, ";")) !== FALSE) { 
    // array_combine 
    // Creates an array by using one array for keys and another for its values 
    $entities[] = array_combine($header, $values);  
} 
+0

這不起作用。標題是一個大字符串,所有列標題都用','分隔。它不會產生我的問題的結構。 –

+0

您問題中的CSV使用';'。更改我的代碼中的分隔符以匹配CSV中使用的分隔符。 –

+0

http://dpaste.com/867987/這是輸出 –

0
$entities = array(); 
//Assuming you are able to get proper array from CSV 
$data = array('title;firstName;lastName;email;', 'Sir;Bob;Public;[email protected];'); 
$num = count($data); 

for ($c = 0; $c < $num; $c++) { 

$line = array(); 
//save first row 

foreach (explode(';', $data[$c]) as $field) { 
    //dont save empty fields 
    if ($c == 0) { 
     if ($field != "") { 
      $fields[] = $field; 
      //$line[$field] = array(); 
     } 
    } else { 
     if ($field != "") { 
      $line[$field] = $field; 
     } 
    } 

} 
if (count($line) > 0) 
    $entities[] = $line; 
}