简体   繁体   中英

PHP probleme while remove columns in csv

I use the php script below to remove some columns from a csv, order them new and save it as new file. And it works for the file i made it for. Now i need to do the same with another csv but i don't know whats wrong. I always get a comma befor the data in the first column.

This is what i have, but it doesn't really work.

<?php
$input = 'http://***/original.csv';
$output = 'new.csv';

if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');

while (false !== ($data = fgetcsv($ih))) {
    // this is where you build your new row
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData);
}

fclose($ih);
fclose($oh);
}

The original.csv looks that:

subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
05096470000         4024144513543   J                   3               6           35016
ae214               848518017215    N       23          0               7           35015
05097280000         4024144513727   J                   1               32          34990

The seperator is ';'. The same seperator is used in the file that is working

But here it will be go wrong because my saved new.csv looks like this:

subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
,05096470000        4024144513543   J                   3               6           35016
,ae214              848518017215    N       23          0               7           35015
,05097280000        4024144513727   J                   1               32          34990

But what i need is a new csv that looks like this:

  qty_estimate  subproduct_number
  3             05096470000
  0             ae214
  1             05097280000

As you can see, i need only the 5. column ($data[4]) as first and the first column ($data[0]) as the second one.

I hope someone can point me in the reight direction. Thanks

You can do so:

while (false !== ($data = fgetcsv($ih))) {
    $data = explode(';', $data[0]);
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData, ';');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM