dongluo9156 2013-05-31 19:21
浏览 148
已采纳

php json保存并读取多个数组到文件

I am trying to save multiple php arrays one at a time. The arrays come to me from a parser function also one at a time. I used to keep them all in memory and then write them all at once like this:

while($onearr = parser())
     $allarr[] = $onearr;

  ..
  ..
  fwrite($filename,json_encode($allarr));

But this logic did not hold for long. I started running out of memory quickly. I want to write the arrays one at a time to the same file and read them one at a time too. This is my writer function:

function savearr($onearr) {        
    if($fp = fopen('arrFile.json','a+'))  {    
       $rc = fwrite($fp, json_encode($onearr));
       fclose($fp);
    }   
}

Now I cannot figure a way to read these arrays! Any way to do it? I tried reading the whole file at once but was not sure how to parse it correctly into individual arrays to match the original!

Thanks in advance

  • 写回答

1条回答 默认 最新

  • doulv8162 2013-05-31 19:29
    关注

    Firstly, you may want to rethink your savearr() function, you're opening/closing the file each time you write the array. Perhaps a class note: none of this was tested:

    class ArrayWriter {
      protected $fp;
      public function __construct() {
        $this->fp = fopen('arrFile.json', 'a+');
        if(!$this->fp) die("Unable to open file");
      }
    
      public function __destruct() {
        if($this->fp) fclose($this->fp);
      }
    
      public function write($array = array()) {
        if($this->fp) fwrite($this->fp, json_encode($array) . "
    ");
      }
    }
    

    Now that we've cleared that up, we can do the reverse to read:

    function read() {
      $arrays = file('arrFile.json');
      $result = array();
      foreach($arrays as $line)
        $result[] = json_decode($line);
      }
      return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题