[英]Array being saved to file not being properly populated once unserialized
我正在嘗試編寫代碼以接收項目id(int)和折扣百分比(float),然后將它們添加到要存儲到文件中的數組中。 但是,當我查看數組時,從文件中讀取后似乎無法正確返回。
我正在使用以下代碼:
<?php
$myfile = fopen("discountsList.txt", "a+") or die("Unable to open file!");
$discounts = [];
$discounts = unserialize(fread($myfile, "r"));
$discounts ["".$_POST['item']]=[$_POST['percentage']];
//Test Data
/*$discounts = [
"1" => 50.0,
"5" => 15.5
];*/
file_put_contents("discountsList.txt", "");
fwrite($myfile, serialize($discounts));
fclose($myfile);
if (isset($_POST['leave'])) header("Location: index.html");
else header("Location: admin_dashboard.php?status=completed");
exit();
我該如何做,以便一旦從文件中讀取數據后就可以將其正確地存儲到數組中,並將其適當地存儲到文件中。
另外,我嘗試這樣做的方式是,如果已經設置了索引,它將替換值而不是創建新索引。
我能夠解決此問題,刪除所有fopen
, fread
, fwrite
和fclose
語句。
工作代碼應如下所示:
$discounts = [];
$discounts = unserialize(file_get_contents("discountsList.txt"));
$discounts ["" . $_POST['item']] = [$_POST['percentage']];
使用file_get_contents
和file_put_contents
可以讀寫整個文件。 為了一次處理整個文件,這是必需的。
file_put_contents("discountsList.txt", "");
file_put_contents("discountsList.txt", serialize($discounts));
if (isset($_POST['leave'])) header("Location: index.html");
else header("Location: admin_dashboard.php?status=completed");
exit();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.