这里只需要一些关于我的问题的帮助。我试图在文本文件中创建一个简单的更新。
我的目标是:
我在更新时遇到问题。我使用array_replace()函数来执行此操作,但它总是添加一个新行。我的更新总是附加到文本文件。
这是我的代码,希望你能帮助我。
//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);