PHP - 每次我保存到文件时,旧数据都会被覆盖
PHP - Everytime I save to file the old data gets overwritten
$testarray['player1'] = $player1Plays;
$testarray['player2'] = $player2Plays;
$testarray['result'] = $result;
print_r ($testarray);
$yoyo = serialize ($testarray);
$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);
我正在为 class 制作一个剪刀石头布小游戏,需要将每一步和结果保存到一个文件中。这是我到目前为止所拥有的,它可以序列化数据并将其保存到文件中,但每次我再次玩游戏时它都会覆盖文件中当前的数据(我认为 'FILE_APPEND' 应该添加在)。此处提供完整代码 https://eval.in/624620
使用 fopen
功能的正确模式很重要。你需要像这样把指针(你可以把它想象成一个写头)放在文件的末尾:
fopen($file, 'a');
查看文档以了解所有可能的模式。
改变
$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);
要么
$fp = fopen('prevdata.dat', 'a'); fwrite($fp, trim($yoyo));
或
file_put_contents('prevdata.dat', trim($yoyo), FILE_APPEND);
$testarray['player1'] = $player1Plays;
$testarray['player2'] = $player2Plays;
$testarray['result'] = $result;
print_r ($testarray);
$yoyo = serialize ($testarray);
$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);
我正在为 class 制作一个剪刀石头布小游戏,需要将每一步和结果保存到一个文件中。这是我到目前为止所拥有的,它可以序列化数据并将其保存到文件中,但每次我再次玩游戏时它都会覆盖文件中当前的数据(我认为 'FILE_APPEND' 应该添加在)。此处提供完整代码 https://eval.in/624620
使用 fopen
功能的正确模式很重要。你需要像这样把指针(你可以把它想象成一个写头)放在文件的末尾:
fopen($file, 'a');
查看文档以了解所有可能的模式。
改变
$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);
要么
$fp = fopen('prevdata.dat', 'a'); fwrite($fp, trim($yoyo));
或
file_put_contents('prevdata.dat', trim($yoyo), FILE_APPEND);