我的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);
}
這給沒有錯誤,但是,這似乎是搞砸了一個怪陣。任何想法如何能得到我想要的結構?
你有一個';'分隔的文件還沒有要指定的','作爲分隔符。 –
謝謝,我編輯了我的問題 –
[CSV到關聯數組]的可能重複(http://stackoverflow.com/questions/4801895/csv-to-associative-array) – ManseUK