2

How would I use the first line of the CSV that I'm processing with fgetcsv() as the key to the array I'm putting each line into? So rather than having my element keys $line[0], $line[6] etc I can just use $line['order-id'] and $line['purchase-date'].

This is only because sometimes the data source I'm using switches the rows around, so they need to be referenced by the column name to ensure I'm selecting the right data. Here is the code I'm currently using:

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

Here is a sample of the CSV I'm using:

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  
James
  • 1,088
  • 3
  • 11
  • 29

1 Answers1

3

Your fgetcsv() doesn't look correct. You either need "\t" for a tab or for 3 spaces. I have no idea what you're doing with the attempt at a newline \n.

Get the first line and combine:

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

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

Or for only certain columns:

$array[] = array(
                    $keys[0]  => $line[0],
                    $keys[11] => ucwords($line[11]),
                    $keys[6]  => $line[6],
                    $keys[10] => $line[10]
);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87