【问题标题】:Compare 2 csv files with php and return changed row numbers将 2 个 csv 文件与 php 进行比较并返回更改的行号
【发布时间】:2014-10-17 03:30:34
【问题描述】:

我有比较 2 个 csv 文件并将更改的行 ID 放入数组的脚本:

 //Function for comparing two files
 function row_compare($a, $b)
 {
 if ($a === $b)
 {
 return 0;
 }
 return (implode("",$a) < implode("",$b) ) ? -1 : 1;
 }

 //Set previous csv file
 $file1 = new SplFileObject("file1.csv");
 $file1->setFlags(SplFileObject::READ_CSV);

 //Set new csv file
 $file2 = new SplFileObject("file2.csv");
 $file2->setFlags(SplFileObject::READ_CSV);

 foreach ($file1 as $row)
 {
 $csv_1[] = $row;
 }

 foreach ($file2 as $row)
 {
 $csv_2[] = $row;
 }

 //Check differences
 $all_unique_rows = array_udiff($csv_1, $csv_2, 'row_compare');

 //Get rows id which have difference
 foreach($all_unique_rows as $key=>$unique_row)
 {
 foreach($unique_row as $element)
 {
 $rowwwithdiffer[] = array($key);
 }
 }

效果很好!但我想要实现的 - 而不是得到 1、2、3 - 使用 1 - 3,它是 - 如果更改的行是连续的,则使用间隔而不是每个更改的行 id...

我怎样才能实现它? ;-)

TNX!

【问题讨论】:

    标签: php csv


    【解决方案1】:

    您必须使用 id 遍历数组并检查它们是否是连续的,并相应地处理它们。

    $aglutinatedRows = [];
    $lastRowId = $rowwwithdiffer[0];
    $firstRowInSequence = $rowwwithdiffer[0];
    
    foreach(array_slice($rowwwithdiffer, 1) as $row) {
        if ($row == $lastRowId + 1) {
            $lastRowId = $row;
        } else {
            $aglutinatedRows[] = $firstRowInSequence != $lastRowId ? $firstRowInSequence . ' - ' . $lastRowId : lastRowId;
            $firstRowInSequence = $row;
            $lastRowId = $row;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2021-07-20
      • 2016-10-18
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多