2014-07-19 11:28
浏览 7


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


$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
echo '</table>'; //end table


All i get is blank output

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyi1111
    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;
        public function accept()
            return !empty(
                    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");
    $filteredFile = new RowContainsValuesFilter($file, $sku);
    foreach ($filteredFile as $row) {
        // this will only give rows for which the filter criteria apply


    点赞 评论