0

I have script which was reading two variable from CSV and those variable was at column 0 and column 5 and it was fine:

$file = fopen($qtyfile,"r");
output("reading file $qtyfile");

$i=0;
$imported = 0;
$failed = 0;
while(! feof($file))
{
  $i++;

  $line = (fgetcsv($file));

  if($i==1) continue;

  $cols = explode(';',$line[0]);


  $pcode = $cols[0];
  $stock = $cols[5];                  

The CSV file has been orginzed in different way, and the variable now at column 16 & 19 i tried to modify the code to the following but it's not working :

$file = fopen($qtyfile,"r");
output("reading file $qtyfile");

$i=0;
$imported = 0;
$failed = 0;
while(! feof($file))
{
  $i++;

  $line = (fgetcsv($file));

  if($i==1) continue;

  $cols = explode(';',$line[0]);


  $pcode = $cols[16];
  $stock = $cols[19];                  

can you please help to make the script ready from new column.

any help will be appreciated.

Link to full script and the csv:

7
  • 1
    Show us a sample of the CSV file. Commented Nov 13, 2017 at 18:52
  • 1
    What error are you getting? Please post the error message. If there isn't an error, is it the wrong data? Possibly the wrong col indexes? We cannot say without a CSV sample and more information regarding the problem. Commented Nov 13, 2017 at 18:56
  • How is it not working? is there an error? Is it reading the wrong data? Commented Nov 13, 2017 at 18:58
  • am going to post the csv old & new and the full script here, when am running the script it say the product not found as the column 16 is the product SKU and the script should lookup the db and find that SKU but if i copied the column 16 to column 0 the script run normally Commented Nov 13, 2017 at 19:02
  • Is the first row of the CSV file the names of the columns? Commented Nov 13, 2017 at 19:08

1 Answer 1

1

Here's an awesome little function which will parse any csv file into an associative array with column titles from row 1 as array keys.

function csvArray($file) {
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      $a = array_combine($csv[0], $a);
    });
    array_shift($csv);
return $csv;
}

Usage:

$output = csvArray($file);
foreach ($output as $o) {
echo $o['pcode'];
// whatever
}

I have to deal with quite a lot of csv files and I use this all the time. Once the data is in an array it's much easier to deal with, and it doesn't matter if columns get moved around as long as the name stays the same it won't break your code.

Sign up to request clarification or add additional context in comments.

Comments

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.