1

For the following CSV file (3MB): ACDF_cut.csv

And for the following code:

<?php

$file = fopen("ACDF_cut.csv","r");
$file2 = fopen("ACDF_cut_rounded.csv","w");


    /* Map Rows and Loop Through Them */
    $rows   = array_map('str_getcsv', file('ACDF_cut.csv'));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }



foreach ($csv as &$product){//Use of & as per https://stackoverflow.com/a/40913938/9095603
    $product['LQ Price'] = number_format($product['LQ Price'],2); 
    $product['AvailableQty'] = number_format($product['AvailableQty']); 
    $product['Net Weight'] = number_format($product['Net Weight'],2); 
}


foreach ($csv as $product) {
  fputcsv($file2, $product);
}


 fclose($file);
 fclose($file2);

I get

[03-Jan-2020 17:00:16 UTC] PHP Warning: array_combine(): Both parameters should have an equal number of elements in /home/kalugi/public_html/wp-content/uploads/wpallimport/files/round_ACDF_cut.php on line 20

I can't see how it's possible that $header and $row don't have an equal number of elements.

But indeed on checking I see that:

echo count($header) = 13
echo count($rows) = 8552

Yet they derive from the same non-ragged CSV file where the number of headers matches the number of fields on each row. To make matters more confusing, I've operated on this same file before and never had issues with unequal header and row counts. How do I fix this?

8
  • I suspect the problem is that file() doesn't recognize the newlines in the file, so it put everything in one line. What is count($rows)? Commented Jan 3, 2020 at 18:21
  • 1
    You have a newline on line 8446 of your csv in the Description1 field that's breaking your import. I'm guessing that may not be the only one. Commented Jan 3, 2020 at 18:24
  • Though, why are you using the file function and str_getcsv, when you can just use fgetcsv on $file? Commented Jan 3, 2020 at 18:28
  • @Barmar $rows count = 8552 ($header count = 13) Commented Jan 3, 2020 at 18:33
  • 1
    count($rows) is irrelevant, what matters is count($row) on every row. Commented Jan 3, 2020 at 18:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.