在读取和写入json文件时执行缓慢

时间:2016-08-21 14:30:52

标签: php

我目前在下面粘贴的代码简单地(或者不那么简单)读取现有的json文件,并在' [']之后将新记录添加到文件中。字符,所以跳过一行。问题是整个读写过程产生非常缓慢的结果。这是用于骰子游戏,用户角色骰子和分数写入json文件,jquery脚本将文件读入表中。

function writeJson($player, $result, $bet, $betamount, $profit) {
   $id=uniqid();
   $response = array(
      'player'=> $player, 
      'result'=> $result,
      'bet'=>$bet,
      'size'=>$betamount,
      'profit'=>$profit,
      'id'=>$id
    );

   $lines = file('dice.json');
   $oldlines='';
   foreach ($lines as $line_num => $line) {
     $oldlines.=$line."\r\n";
     if($line_num==0) { //insert new record here. 
        $oldlines.=json_encode($response).",\r\n"; 
     }
   }
   file_put_contents('dice.json',preg_replace('/^\h*\v+/m', '', $oldlines));
   clearstatcache();
}

这是由此代码生成的json文件的格式。

    [ 
    new records will be inserted at this location
{"player":"seang","result":"EVEN","bet":"ODD","size":"0.00000005","profit":"-0.00000005","id":"57b9ace6ce133"},
    {"player":"seang","result":"EVEN","bet":"ODD","size":"0.00000005","profit":"-0.00000005","id":"57b9ace1c73f4"},
    {"player":"seang","result":"ODD","bet":"ODD","size":"0.00000005","profit":"+0.00000005","id":"57b9acd8dd50a"}
    ]

0 个答案:

没有答案