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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真