dongpiao9078 2017-10-27 14:21
浏览 44


Is there way to append data to file on specific line or something similar like that?

I have an "handmade" array in my file, and I need to keep my beginning and end of the array.

I would like to have something like this:

$array = [
    *create new line and write data here*,
*previous data*,
*previous data*,
*previous data*,

EDIT: I currently only know how to append data at the end of the file, and I haven't found proper solution. If I append my data with just file_put_contents();, it won't be in the array:

$array = [
    *previous data*,
    *previous data*,
    *previous data*,
*create new line and write data here*,

EDIT: I got my answer. There is no efficient way to do this.

  • 写回答

3条回答 默认 最新

  • dongyuruan2957 2017-10-27 14:50

    If writing to a file, there are not many (any, in my personal experience!) options for efficient prepending or mid-file inserts. Almost all of the working world relies on appending to files. You can do it, but only through basically rewriting the entire file. In essence, you have to "move all the other lines down", and that takes work.

    If this is something you need done efficiently, consider a more appropriate data structure. Perhaps multiple arrays (e.g., perhaps in reverse order), multiple files, a sorting key for after load sorting, etc. But you are not likely to get around the issue of slow performance when prepending or inserting to on-disk files. (And if you do, likely involving some kernel editing, then consider making some money or helping the FOSS world out!)

    If you are doing this in memory, then the data structures and access patterns are much more robust, and so you can do operations like array_unshift:

    $arr = [
      "line 1",
      "line 2",
      "line ..."
    array_unshift($arr, "line 0");
    # $arr is now: [
    #  "line 0",
    #  "line 1",
    #  "line 2",
    #  "line ..."
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥20 matlab如何绘制三维瀑布图
  • ¥15 关于用abap来解决动态规划的问题,但是要求输出索引值,这个是难点
  • ¥15 在ISIS中什么是IP从地址
  • ¥15 压测时,并发量过高时,响应时间出现尖刺
  • ¥15 关于vmprotect3.8.4虚拟文件一项
  • ¥15 在不用IT调试的情况下怎样能连外网
  • ¥20 C#调用虚拟键盘TabTip.exe
  • ¥15 Qt4代码实现下面的界面
  • ¥15 CCS离散化传递函数与仿真不一致
  • ¥15 prism提示我reinstall prism 如何解决