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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大