使用 PHP 从 CSV 中删除一列中有多个相似 ID 的行

卡斯帕

我遇到了 CSV 和 PHP 的问题,而且我对 CSV 的总体经验有限。我有一个包含数据的 CSV 文件:

name;id;date
john;222;17.07.2018
john;222;29.10.2018
mary;333;01.11.2018
mary;333;02.11.2018
steve;444;05.11.2018
kyle;555;06.11.2018
.
.

我想删除(或跳过)所有 ID 出现多次的行。

这意味着 ID 为222、333 的所有行都将被删除,而 ID 为444、555 的(因为ID 444 和 555出现一次出现在列中)将写入新文件。

我的目标是:

name;id;date
steve;444;05.11.2018
kyle;555;06.11.2018
.
.

我可以自己写入文件并将 csv 加载到 PHP,但我正在努力找到一种正确的方法来过滤它们,就像我上面提到的那样

我用谷歌搜索并尝试了许多 StackOverFlow 示例,但这些只是过滤唯一的行(显示 ID 222,333,444,555),而不是过滤 ID 仅在列中出现一次的行。

谢谢!

阿萨德·乌拉·查

您可以使用二维数组来完成它。您可以逐行读取文件,分解每一行并仅从每一行中选取第二个子字符串 (id) 并将其用作外部数组的索引名称,并继续将内部数组中的值存储在同一索引上。

您的二维数组转储应如下所示:

Array
(
    [id] => Array
        (
            [0] => name;id;date
        )

    [222] => Array
        (
            [0] => john;222;17.07.2018
            [1] => john;222;29.10.2018
        )

    [333] => Array
        (
            [0] => mary;333;01.11.2018
            [1] => mary;333;02.11.2018
        )

    [444] => Array
        (
            [0] => steve;444;05.11.2018
        )

    [555] => Array
        (
            [0] => kyle;555;06.11.2018
        )

)

接下来,您需要遍历这个数组,并且只在每个索引为 1 的索引上选取数组。

这是完整的代码:

// array to hold lines 
$lines = [];

// string type variale to hold final result
$contents = '';


// open the csv file
if (($handle = fopen("test.csv", "r")) !== false) {
    // read each line into an array
    while (($data = fgetcsv($handle, 8192, ",")) !== false) {

        // explode the string on semicolons
        $segment = explode( ';', $data[ 0 ] );

        // pick the second substring (the id) and use it as index in the $lines array and assign the read line to it
        $lines[ $segment[ 1 ] ][] = $data[ 0 ];

    }
    fclose($handle);
}



foreach( $lines as $line ){
    // only pick the inner arrays with one element to remove all double records.
    if( count( $line ) == 1 ){
        $contents .= $line[0] . "\r\n";
    }
}

file_put_contents("unique_file.csv", $contents);

让我知道它是怎么回事。

祝你好运;)

记住!如果您有一个小的 .csv 文件,这个解决方案是可以的。对于较大的文件,还有其他解决方案。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章