2014-03-01 28 views
0

從PHP中的CSV文件創建數組。然而,正如預期的那樣,產出正在增加數字。如何從CSV中檢索後將專有名稱分配給數組項目

這裏是我的代碼

 $file = @fopen('customers.csv', 'r'); 

    // Create arrays from the CSV file 
    echo '<pre>'; 
     while (($line = fgetcsv($file)) !== FALSE) { 

      $customers[] =$line; 
     } 
    echo '<pre>'; 
    print_r($customers); 

此輸出。

Array 
(


[0] => Array 
    (
     [0] => 148 
     [1] => 0 
     [2] => Adrian 
     [3] => de Cleir 


    ) 

[1] => Array 
    (
     [0] => 305 
     [1] => 0 
     [2] => John 
     [3] => Smyth 

    ) 

[2] => Array 
    (
     [0] => 49 
     [1] => 0 
     [2] => adrian 
     [3] => O'malley 

    ) 
) 

寫這個信息到數據庫中的還要好不得使用數字....

例如,當

[0] => Array 
    (
     [customer_id] => 148 
     [store_id] => 0 
     [first_name] => Adrian 
     [second_name] => de Cleir 


    ) 

回答

1

在你while循環:

while (($line = fgetcsv($file)) !== FALSE) { 
    $customers[] = array(
     'customer_id' => $line[0], 
     'store_id' => $line[1], 
     'first_name' => $line[2], 
     'second_name' => $line[3], 
    ); 
}