2015-09-17 24 views
1

我將如何使用我正在使用fgetcsv()處理的CSV的第一行作爲我將每行放入的數組的鍵?所以,而不是讓我的元素鍵$line[0]$line[6]等我可以只使用$line['order-id']$line['purchase-date']使用第一行CSV作爲數組鍵

這只是因爲我使用的數據源有時會切換行,所以需要通過列名引用它們以確保選擇正確的數據。這是我目前使用的代碼:

// create a new array that will be a child to $array for each order, contains details. 
while (($line = fgetcsv($file,'',' ','\n')) !== FALSE) { 
    // count (for email later on) 
    if(!isset($count)) { 
     $count = count($line); 
    } 

    // add to new array (subarray) 
    $individualarray = array(
     'order-id' => $line[0], 
     'buyer-name' => ucwords($line[11]), 
     'purchase-date' => $line[6], 
     'email-address' => $line[10] 
    ); 
    $num++; 
    // add to the array of all orders 
    $array[$num] = $individualarray; 
} 
//remove first record from array, these are the headers. 
unset($array[1]); 

// close file 
fclose($file); 

這裏是CSV的樣本,我使用:

amazon-order-id merchant-order-id purchase-date last-updated-date order-status fulfillment-channel sales-channel order-channel url ship-service-level product-name sku asin item-status quantity currency item-price item-tax shipping-price shipping-tax gift-wrap-price gift-wrap-tax item-promotion-discount ship-promotion-discount ship-city ship-state ship-postal-code ship-country promotion-ids 
xxxxx-xxxxx-xxxxx xxxxx-xxxxx-xxxxx 2015-09-17T09:27:35+00:00 2015-09-17T09:27:37+00:00 Pending Amazon Amazon.es   Standard Some product name xx-xxxx-xxxx xxxxxxx Unshipped 1 EUR 19.99        Huelva Huelva xxxxx ES  
xxxxx-xxxxx-xxxxx xxxxx-xxxxx-xxxxx 2015-09-17T17:35:28+00:00 2015-09-17T17:35:29+00:00 Pending Amazon Amazon.co.uk   Expedited Another Product Name xx-xxxx-xxxx xxxxxxx Unshipped 1 GBP 14.99        Eastleigh Hampshire xxxx xxx GB 

回答

1

fgetcsv()看起來並不正確。您需要"\t"爲一個標籤或 3個空格。我不知道你在嘗試換行\n

獲取的第一行,並結合:

// get first line 
$keys = fgetcsv($file, 0, "\t"); 

while (($line = fgetcsv($file, 0, "\t")) !== FALSE) { 
    $array[] = array_combine($keys, $line); 
} 

還是僅針對特定列:

$array[] = array(
        $keys[0] => $line[0], 
        $keys[11] => ucwords($line[11]), 
        $keys[6] => $line[6], 
        $keys[10] => $line[10] 
); 
+0

另見http://stackoverflow.com/questions/4260086/php-how-to- use-array-filter-to-filter-array-keys不必硬編碼列號。 – bernie

+0

嘗試了下面的代碼,它返回了很多bool(false)值。 http://pastie.org/private/2c6v6ky4hhctsrn8pmeg – James

+0

我不知道你的文件是什麼樣子。它要麼格式不正確,要麼'fgetcsv()'參數不正確。 – AbraCadaver

相關問題