简体   繁体   中英

How to make sure that no word is repeated in a csv file using php?

I have a .csv file like this

file.csv

green,yellow,blue,white

these values will change dynamically during runtime but stays in the same format in the single first line in the file.csv.

During runtime sometimes it comes like this

green,blue,violet,violet,blue

that means some of these values are repeating and that should not have happened in the file.

Is there anyway which will prevent the word repetition using php.?

what I have done so far is given below which seems to be wrong

First I took the file into an array , $color
$array=array();
foreach($color as $col1)
   {
      foreach($color as $col2)
      {
         if(strcmp($col1,$col2)!=0)
         {
            $array=$col1;
         }
      }
   }
file_put_contents('file.csv',$array);

I know this doesn't have any logic, but this is what i could do as a pioneer .

$array=array();
foreach($color as $col1) {
    $array[] = $col1;
}
file_put_contents('file.csv',array_unique($array));

This should be

$file = 'file.csv';
file_put_contents($file, join(',', array_unique(explode(',', file_get_contents($file)))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM