dongxian8272 2014-07-19 11:28
浏览 7
已采纳

将csv与数组进行比较

I am trying to compare csv data against my array, so the csv ocuk has about 7000 lines and i want to only display data from the csv that matches the $sku array, the array will eventually have about 500 items and will go to database array later but for now i just want it to function correctly

<?php

$sku = array("WC-564-EK","WC-562-EK");
echo '<table>'; //start table
$ocuk = fopen("ocuk.csv", "r");
while (($csv = fgetcsv($ocuk, 10000, ',')) !== FALSE)
{
   foreach ($sku as $var)
   {
      for ($i=; $i<=10000; $ii)
      {
         if (strtolower ($var)==strtolower($csv[$i]))
         {
            echo '<tr><td>',$csv[0], //brand
            '</td><td>',$csv[1], //stockcode
            '</td><td>',$csv[2], //desc
            '</td><td>',$csv[3], //quantiy
            '</td><td>',$csv[4], //resellerprice
            '</td><td>',$csv[5], //ean
            '</td><td>',$csv[6], //mpn
            '</td></tr>';
          }
      }
  }
}
fclose($handle);
echo '</table>'; //end table

?>

All i get is blank output

  • 写回答

1条回答 默认 最新

  • dongyi1111 2014-07-19 11:42
    关注

    Instead of that while/foreach/for/if check, try with

    while (($csv = fgetcsv($ocuk)) !== FALSE)
    {
        if (false === empty(array_intersect($sku, array_map('trim', $csv)))) {
            echo …
        }
    }
    

    As an alternative, consider

    class RowContainsValuesFilter extends FilterIterator
    {
        private $valuesToSearchFor;
    
        public function __construct(Iterator $iterator, array $valuesToSearchFor)
        {
            $this->valuesToSearchFor = $valuesToSearchFor;
            parent::__construct($iterator);
        }
    
        public function accept()
        {
            return !empty(
                array_intersect(
                    $this->valuesToSearchFor,
                    array_map('trim', $this->current())
                )
            );
        }
    }
    

    Encapsulating the filter logic this way, makes it easy to reuse the logic wherever you need it without having to put the comparison at the place you use it. This makes changing the logic at a later stage much easier. All you'd do with the above is this:

    $sku = array("WC-564-EK","WC-562-EK");
    $file = new SplFileObject("ocuk.csv");
    $file->setFlags(SplFileObject::READ_CSV);
    $filteredFile = new RowContainsValuesFilter($file, $sku);
    
    foreach ($filteredFile as $row) {
        // this will only give rows for which the filter criteria apply
    }
    

    Reference:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)