John Davidson

csv - How to remove duplicates from a PHP string separated by "X"?

0 comments
Message:


I have a csv file that looks like this:


13:BOOT2700        X;27
13:BOOT2700 X;27
13:BOOT2700 X;27
13:BOOT2700 X;27
13:BOXER1136 X;11.36
13:BOXER1364 X;13.64
13:BOXER1591 X;15.91
13:BOXER909 X;9.09
...

I would like to remove the duplicates of data[0] and remove the spaces and the "X" at the end of the string. For the second part it works correctly but I can't delete the duplicates. I tried this code but they remain. It shows me each time the first values while they are identical.


In the end I would like this:


13:BOOT2700;27
13:BOXER1136;11.36
13:BOXER1364;13.64
13:BOXER1591;15.91
13:BOXER909;9.09

How can I do it?
Thanks for your help


<?php

$file = "BI6_20211214_0905_15000.txt";

if (($handle = fopen($file, "r")) !== false) {



while (($data = fgetcsv($handle, 9000000, ";")) !== false) {

$uniqueStr = implode('X', array_unique(explode('X', $data[0]))); //doesn't work

$clean_name = str_replace(' ', '', $data[0]);
$clean_name2 = str_replace('X', '', $clean_name);

echo $clean_name2; //13:BOOT2700
echo ("<br>");

}
}
fclose($handle);


echo "good !";


?>


My Answer:
To remove duplicates from the first column of your CSV file, you can use an array to keep track of the unique values and only output them once. Here's an updated version of your code that should achieve the desired result:

php
$file = "BI6_20211214_0905_15000.txt";
$uniqueValues = array();

if (($handle = fopen($file, "r")) !== false) {
while (($data = fgetcsv($handle, 9000000, ";")) !== false) {
$clean_name = str_replace(' ', '', $data[0]);
$clean_name2 = str_replace('X', '', $clean_name);

if (!in_array($clean_name2, $uniqueValues)) {
echo $clean_name2 . ";" . $data[1];
echo "
";
$uniqueValues[] = $clean_name2;
}
}
fclose($handle);
}

echo "good!";


In this code, we use the `$uniqueValues` array to keep track of the unique values in the first column. If a value has not been seen before, we output it along with the corresponding second column value and add it to the `$uniqueValues` array. This way, duplicates are removed from the output.

Rate this post

5 of 5 based on 2608 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us