简体   繁体   English

修改PHP脚本以从CSV文件读取

[英]Modify PHP script to read from CSV file

I have script which was reading two variable from CSV and those variable was at column 0 and column 5 and it was fine: 我有从CSV读取两个变量的脚本,这些变量在第0列和第5列,很好:

$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 : CSV文件已经以不同的方式编排,并且现在位于第16和19列的变量我试图将代码修改为以下内容,但是它不起作用:

$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: 链接到完整脚本和csv:

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. 这是一个很棒的小功能,它将任何csv文件解析为一个关联数组,其中第1行的列标题作为数组键。

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. 我必须处理大量的csv文件,并且我一直都在使用它。 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. 数据放入数组后,处理起来会容易得多,只要名称保持不变,列是否移动也不会影响代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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