php - 使用 CSV 的第一行作为数组键

标签 php csv fgetcsv

如何使用我正在使用 fgetcsv() 处理的 CSV 的第一行作为我将每行放入的数组的键?因此,我可以使用 $line['order-id']< ,而不是使用我的元素键 $line[0]$line[6]$line['购买日期']

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

// 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  

最佳答案

您的 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]
);

关于php - 使用 CSV 的第一行作为数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636559/

相关文章:

php - 无法通过 Adwords API 获取广告的目标网址

php - MySQL 循环选择

python - 如果使用 pandas 的几行满足某些条件,如何删除行

mysql - 在 MySql 中导入 CSV 文件时使用的正确路径

php - 读取 csv 文件的最快方法

php - 在适用于 Linux 的 XAMPP 中升级 PHP?

结构中的 C malloc

php - 导入包含日期或文本列的 CSV 文件

php - fgetcsv 返回太多条目

php - 带下一个/上一个按钮的下拉菜单 php