简体   繁体   English

数组未序列化后保存到文件中的信息未正确填充

[英]Array being saved to file not being properly populated once unserialized

I am trying to write code to receive an item id(int) and a discount percentage(float) then add them into an array which is meant to be stored into a file. 我正在尝试编写代码以接收项目id(int)折扣百分比(float),然后将它们添加到要存储到文件中的数组中。 However when I look at the array, it doesn't seem to e returned properly once read from the file. 但是,当我查看数组时,从文件中读取后似乎无法正确返回。

I am using the following code: 我正在使用以下代码:

    <?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();

How can I make it so I could store the data properly into an array once it is read from the file and also store it into the file appropriately. 我该如何做,以便一旦从文件中读取数据后就可以将其正确地存​​储到数组中,并将其适当地存储到文件中。

Also the way I am trying to do it is so that if the index already has been set that it replaces the value instead of making a new index. 另外,我尝试这样做的方式是,如果已经设置了索引,它将替换值而不是创建新索引。

I was able to to solve this removing all fopen , fread , fwrite , and fclose statements. 我能够解决此问题,删除所有fopenfreadfwritefclose语句。

The working code should look something like this: 工作代码应如下所示:

$discounts = [];
$discounts = unserialize(file_get_contents("discountsList.txt"));
$discounts ["" . $_POST['item']] = [$_POST['percentage']];

Using the file_get_contents and file_put_contents you are ale to read and write to the whole file; 使用file_get_contentsfile_put_contents可以读写整个文件。 this is required in order to take care of the whole file at a time. 为了一次处理整个文件,这是必需的。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM