Hello guys,
Just need a little help here about my problem. I am trying to create a simple update in a textfile.
My goal is:
- If the data is existed in the textfile. Don’t add a new line in the file instead update that certain line.
- If data is not existed simple add a new line in the file.
I have a problem in updating. I used the array_replace() function to do this but it always add a new line.
Here’s my code I hope that you can help me.
[php] //This is the new array from the user
$data_add = array(
‘restaurant_id’ => $restaurant_id,
‘new_lat’ => $new_lat_entry,
‘new_long’ => $new_long_entry,
‘date_updated’ => date(‘Y-m-d H:i:s’)
);
//This is the base array - It will get the text file if exsited
$data = unserialize(file_get_contents('addresses.txt'));
//get the ID of the new array - use for validation
$target = $data_add['restaurant_id'];
//loop the abase array
for ($i = 0; $i < count($data); $i++) {
//get the ID of the base array
$get_id = $data[$i]['restaurant_id'];
//compare base array ID and new array ID
if($get_id == $target){
// IF FOUND IN THE TEXTFILE
$add_data = array();
$add_data = array(
$i => $data_add
);
//replace the existed array in textfile with my updated array
$new_array = array();
$new_array = array_replace($data,$add_data);
//break;
}else{
//IF NOT FOUND, SIMPLY ADD
$new_array = array(
$i => $data_add
);
//fn_print_die($new_array);
}
}
//FOR DISPLAYING PURPOSES
echo "<pre>";
echo "BASE ARRAY<br />";
print_r($data);
echo "---------------------------------------------------------<br />";
echo "NEW ARRAY<br />";
print_r($add_data);
echo "---------------------------------------------------------<br />";
echo "REPLACED ARRAY<br />";
print_r($new_array);
echo "---------------------------------------------------------<br />";
//exit;
//SERIALIZE THE UPDATED ARRAY
$serialize_data = serialize($new_array);
//WRITE THE TEXTFILE
$file_input_txt = fopen("addresses.txt","a+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
//exit;
$array = unserialize(file_get_contents('addresses.txt'));
$file_input = fopen("addresses.csv","a+");
fputcsv($file_input, $data_add);
fclose($file_input);
[/php]