您可以使用2D阵列完成此操作。您可以逐行读取文件,展开每一行,然后仅从每一行中选择第二个子字符串(id),并将其用作外部数组的索引名称,并继续将内部值存储在同一索引上。
您的2D阵列转储应如下所示:
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文件,则此解决方案是可以的。对于较大的文件,还有其他解决方案。
本文链接:https://www.f2er.com/3116866.html