Home > Mobile >  PHP append duplicate value
PHP append duplicate value

Time:03-02

I'm trying to append data in file
I have an array result contains this value :

Array ( [0] => Array ( [name] => Fanny [asset] => 1034 ) ) Array ( [0] => Array ( [name] => Gabriel [asset] => 1089 ) ) Array ( [0] => Array ( [name] => Martin [asset_no] => 1520> ) ) 

I use a foreach to get the values and then insert them in a file :

foreach ($result as $value){
  $name = $value['name'];
  $asset = $value['asset'];
  $dir = "C:/Users/<users>/data";
  if (!is_dir($dir)) {
    mkdir($dir,0777);
  }
file_put_contents("$dir/data", "$name , $data \r", FILE_APPEND);

The data in my data file is :

Fanny, 1034
Gabriel, 1089
Martin, 1520

When I rerun my file it duplicates the values in the file that stores my data:

Fanny, 1034
Gabriel, 1089
Martin, 1520
Fanny, 1034
Gabriel, 1089
Martin, 1520

I would like to prevent duplication for existing values
Can anyone tell me where the error. Thank you for your help !

CodePudding user response:

you need to remove FILE_APPEND parameter as it appends data to the end of the file , as you are re-inserting all data again and again you don't need old data so you can remove it thus file_put_contents will remove old file data and store the new data instead

if you need to compare old data stored in the file and new data in array I would suggest you read data from file first , convert it to array ( with json_decode maybe ) and create a function to loop through 2 arrays and append values that doesn't exist

CodePudding user response:

To resolve my problems i have use one array with data and compare my data i want to add that i wanted to insert :

$file = file_get_contents("$dir/data");
$data = explode("\r",$file);
foreach ($result as $value) {
  $name = $value['name'];
  $asset = $value['asset'];
  $message = "$name, $asset";
  if (in_array($message, $data)){
     echo "$message already exist ";
  } else {
     file_put_contents("$dir/data", "$message\r", FILE_APPEND);
  }
}
  • Related