PHP CSV重复值

问题描述 投票:1回答:1

我有一个csv文件,其中包含来自两个分销商的产品数据和价格。此文件中有67个键。现在,我想搜索该文件中所有可用两次的EAN,然后以最低的价格获得。之后,删除其他价格较高的产品线。CSV为我的商人提供了一个密钥。

为了方便查看,我做了一个csv测试:

artno;name;ean;price;merchant
1;ipad;1654213154;499.00;merchant1
809;ipad;1654213154;439.00;merchant2
23;iphone;16777713154;899.00;merchant2
90;iphone;16777713154;799.00;merchant1

脚本运行完后,csv看起来应该像(写入新文件):

artno;name;ean;price;merchant
809;ipad;1654213154;439.00;merchant2
90;iphone;16777713154;799.00;merchant1

我玩过fgetcsv,通过csv循环不是问题,但是我如何在键2中搜索ean?

$filename = './test.csv';
$file = fopen($filename, 'r');
$fileline = 1;

while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($fileline == "1"){ $fileline++; continue; }


$search      = $data[2];
$lines       = file('./test.csv');
$line_number = false;

$count = 0;
while (list($key, $line) = each($lines) and !$line_number) {
   $line_number = (strpos($line, $search) !== FALSE) ? $key : $line_number;
   $count++;
}

if($count > 2){ 
    echo "<pre>",print_r(str_getcsv($lines[$line_number], ";")),"</pre>";
}

}
php csv
1个回答
2
投票

我认为这是您想要的:

<?php
$filename = './test.csv';
$file = fopen($filename, 'r');
$lines = file('./test.csv');
$headerArr = str_getcsv($lines[0], ";");

$finalrawData = [];
$cheapeastPriceByProduct = [];
$dataCounter = 0;

while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
  if($dataCounter > 0) {
    $raw = str_getcsv($lines[$dataCounter], ";");
    $tempArr = [];
    foreach( $raw as $key => $val) {
      $tempArr[$headerArr[$key]] = $val;
    }
    $finalrawData[] = $tempArr;
  }
  $dataCounter++;
}

foreach($finalrawData as $idx => $dataRow ) {
  if(!isset($cheapeastPriceByProduct[$dataRow['name']])) {
    $cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
  }
  else {
    if(((int)$dataRow['price'])< ((int)$cheapeastPriceByProduct[$dataRow['name']]['price'])) {
      $cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
    }
  }
}

echo "<pre>";
print_r($finalrawData);
print_r($cheapeastPriceByProduct);

我刚刚添加了$finalData数据数组来存储已解析的数据,并将所有行与其标头键对应的内容相关联,然后您可以根据自己的条件比较和过滤数据。

© www.soinside.com 2019 - 2024. All rights reserved.