dongluo9156
2013-05-31 19:21
浏览 133

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

图片转代码服务由CSDN问答提供 功能建议

我试图一次保存多个php数组。 这些数组一次只能从一个解析器函数中找到我。 我曾经将它们全部保存在内存中,然后像这样一次写下它们:

  while($ onearr = parser())
 $ allarr [] = $ onearr  ; 
 
 .. 
 .. 
 fwrite($ filename,json_encode($ allarr)); 
   
 
 

但这种逻辑并没有持续多久 。 我开始快速耗尽内存。 我想一次一个地将数组写入同一个文件,并一次读取一个。 这是我的编写函数:

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

现在我无法想象 一种阅读这些数组的方法! 有办法吗? 我尝试一次读取整个文件,但不确定如何将其正确解析为单个数组以匹配原始文件!

提前致谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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;
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题