使用第一行CSV作为数组键

时间:2015-09-17 17:34:19

标签: php csv fgetcsv

我如何使用我用fgetcsv()处理的CSV的第一行作为数组的关键我将每行放入?因此,我可以使用$line[0]$line[6],而不是使用我的元素键$line['order-id']$line['purchase-date']等。

这只是因为有时我使用的数据源会切换行,因此需要通过列名引用它们以确保我选择正确的数据。以下是我目前正在使用的代码:

// 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 I样本:

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 个答案:

答案 0 :(得分: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]
);