Php a在不重新写入整个文件的情况下绑定到缓存文件中的数组

Php a在不重新写入整个文件的情况下绑定到缓存文件中的数组,php,arrays,caching,multidimensional-array,Php,Arrays,Caching,Multidimensional Array,所以我有一个名为cache的文件,它使用多维数组存储站点的流量分析 cache.php $traffic_array=array("date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"),"date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"));//ect ect 现在,我需要以某种

所以我有一个名为cache的文件,它使用多维数组存储站点的流量分析

cache.php

$traffic_array=array("date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"),"date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"));//ect ect
现在,我需要以某种方式附加到上面的数组

我可以简单地读取整个文件,在foreach循环中遍历并重建数组,然后重新写入整个文件,如下所示:

include('cache.php');

foreach($traffic_array as $mainKey){

$rebuild_contents.="array("something"=>array("pageviews"=>".$mainKey['pageviews'].","time_enteredOnsite"=>".$mainKey['time_enteredOnsite'].");"//so I'm just building a string containing all the code to re-write the file.

} 

//then write to the file

$file="cache.php";

$content_to_put"\<? \$traffic_array=\"$rebuild_content\";"

file_put_contents($file,$content_to_put);

//NOTE: I just quickly wrote this up now, so expect syntax errors.
$traffic_array[new key 1] = array(new data 1);
$traffic_array[new key 2] = array(new data 2);
...
include('cache.php');
foreach($traffic\u数组作为$main key){
$rebuild_contents.=“数组”(“something”=>array(“pageviews”=>“$mainKey['pageviews']”),“time\u enteredOnsite”=>“$mainKey['time\u enteredOnsite']”;“//所以我只是在构建一个包含所有代码的字符串来重新写入文件。
} 
//然后写入该文件
$file=“cache.php”;

$content\u to\u put“\这似乎不是一种很好的缓存方式,因为你不得不问这个问题。添加一个新条目应该很容易

我的建议是:

  • 使用名为cache的数据库表,并根据需要添加新行或检索、更改和写入一行

  • 使用一个不包含PHP代码的文件,但包含CSV之类的其他文件,在该文件中,您可以轻松地附加到该文件,而无需担心分号的关闭等问题,您还可以在需要时使用内置的PHP库函数(如fgetcsv())快速读取该文件


  • 这是一种非常奇怪的缓存方法。 假设您希望更改文件中的一些php代码

    file\u put\u内容可以将数据追加到文件末尾,使用标志file\u append()调用此方法。 您可以将定义数组的方法更改为:

    include('cache.php');
    
    foreach($traffic_array as $mainKey){
    
    $rebuild_contents.="array("something"=>array("pageviews"=>".$mainKey['pageviews'].","time_enteredOnsite"=>".$mainKey['time_enteredOnsite'].");"//so I'm just building a string containing all the code to re-write the file.
    
    } 
    
    //then write to the file
    
    $file="cache.php";
    
    $content_to_put"\<? \$traffic_array=\"$rebuild_content\";"
    
    file_put_contents($file,$content_to_put);
    
    //NOTE: I just quickly wrote this up now, so expect syntax errors.
    
    $traffic_array[new key 1] = array(new data 1);
    $traffic_array[new key 2] = array(new data 2);
    ...
    
    然后您只需像这样将内容添加到文件的末尾

    file_put_contents($file, '$traffic_array[your new key] = array(data for adding);', FILE_APPEND);
    
    但是,如果您可能不更改定义数组流量的方法,则文件内容不适合您。使用带有标记“r+”的
    fopen()
    ,使用
    fseek()
    将指针移动到正确的位置,以便在文件中放置新数据,
    fwrite()
    仅写入新数据,以及
    fclose()


    //文件内容:广告编辑:是。使用
    flock()
    防止that@Robus这很有趣-那么我如何检查该文件是否已在使用中?请参阅