一旦被反序列化,保存到文件的数组未正确填充

时间:2018-04-26 14:40:54

标签: php file

我正在尝试编写代码以接收项目ID(int)折扣百分比(浮动),然后将它们添加到一个数组中,该数组将用于存储到一个文件。但是当我查看数组时,从文件读取后似乎没有正确返回。

我使用以下代码:

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

如何创建它,以便在从文件中读取数据后将数据正确存储到数组中,并将其正确存储到文件中。

此外,我尝试这样做的方式是,如果已设置索引,则替换该值而不是创建新索引。

1 个答案:

答案 0 :(得分:0)

我能够解决此问题,删除所有purrr::map_dfr(.x = dat,tibble::enframe,.id = "text") # A tibble: 30 x 3 text name value <chr> <chr> <dbl> 1 blogs new york city 816 2 blogs new york times 609 3 blogs amazon services llc 427 4 blogs services llc amazon 426 5 blogs llc amazon eu 426 6 blogs couple weeks ago 419 7 blogs incorporated item pp 390 8 blogs two years ago 353 9 blogs new york n.y 326 10 blogs world war ii 301 # ... with 20 more rows fopenfreadfwrite语句。

工作代码应如下所示:

fclose

使用$discounts = []; $discounts = unserialize(file_get_contents("discountsList.txt")); $discounts ["" . $_POST['item']] = [$_POST['percentage']]; file_get_contents,您可以读取和写入整个文件;为了一次处理整个文件,这是必需的。

file_put_contents