使用php覆盖文本文件中的单个值



我正在尝试编写一个代码,该代码应该为一个帐户存储一组天数。然后,该帐户的用户应该能够使用html选择特定的时间段。然后,应该从总额中减去这些天数,并将新值放回文本文件中。

到目前为止,我已经尝试过通过将txt文件读取到数组中并从中进行操作来解决很多问题,但这是我遇到的一个死胡同,因为我找不到解决问题的方法。

我现在让它工作的方式是这样的:

if(isset($_POST['submit_btn'])) //If the submit button is pressed, it starts working through the steps
{
$start1 = date_create($_POST["start"]); //I convert the HTML dates to php dates so i can work with them in a second
$end1 = date_create($_POST["end"]);
$start2 = date_format($start1, "Y-m-d");
$end2 = date_format($end1, "Y-m-d");
$end = $end2;
$start = $start2;
$d_diff1 = date_diff(date_create($end), date_create($start)); //I create the date difference and convert them back into a value I can work with
$d_diff = $d_diff1->format('%d days');
$up = fopen('texturlaub.txt', 'a+');
if($d_diff < 0) //The next few lines are technically irrelevant for the problem
{
echo "Ihr Startdatum muss vor dem Enddatum liegen.";
}
elseif($d_diff == 0)
{
echo "Sie können heute keinen Urlaub mehr legen.";
}
elseif($d_diff >= 35)
{
echo "Ihr Antrag wurde gestellt. Aufgrund der Länge dea Beantragten Urlaubs muss dieser erst manuell bestätigt werden. Sie werden innerhalb von 2 Werktagen benachrichtigt.<br>";
}
elseif($d_diff >= 1 && $d_diff <= 35) //Here is where the problem starts
{
echo "Ihr Antrag wurde eingereicht und von System freigegeben. Sollte es Probleme mit ihrem Antrag geben wird sich in den nächsten 2 Tagen ein Mitarbeiter an sie wenden. <br>";
$urlaubkey = str_word_count(file_get_contents('texturlaub.txt'),1,'üöä1234567890-.:;_<>|@€!§%&/=?'); //I read the txt file into the array
}
$key = array_search($name, $urlaubkey); //I check for the username in the array. If I find it, the array key for the username is saved as a variable
echo $key; //Next step would be to increase the value of this by 1 to get the correct key. Then i'd have to overwrite the txt file.

这基本上就是我现在的处境。唯一缺少的是我将数组键增加了一,并运行了简单的子动作,但这并不是的真正问题

我的txt文件保存值的方式如下:

körner,26
werner,26
albert,30
wernher,26
Walther,34

它遵循"用户名"、"剩余天数"的方案

如有任何帮助,将不胜感激

我建议您使用serialize和unserialize函数序列化和反序列化包含数据的数组的内容;这将使您更容易操作阵列的内容

请参阅以下示例代码

<?php
define("FILENAME", "C:TEMPUserList.txt");
// Create an array containing a list of users 
$userList = array(
'USER0001' => array(
'name' => 'Fabio',
'number' => 23,
),
'USER0002' => array(
'name' => 'Laura',
'number' => 7,
),
);
// Serialize the array and write the contents to a file 
file_put_contents(FILENAME, serialize($userList));
// Read the contents from the file and deserialize the array 
$userList = unserialize(file_get_contents(FILENAME));
// Update the value of the 'number' field, identifying the user by its unique key 
$userList['USER0001']['number'] = 75;
// Write once more 
file_put_contents(FILENAME, serialize($userList));
// Read once more 
$userList = unserialize(file_get_contents(FILENAME));
// Dump the result 
echo '<pre>';
var_dump($userList);
echo '</pre>';

最新更新