dongpiao9078 2017-10-27 14:21
浏览 44
已采纳

使用PHP将特定行的数据写入文件

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 ..."
    #];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3