挂起到缓存文件中的数组,而不重写整个文件


apending to an array in a cache file without re-writing the whole file

所以我有一个名为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.

所以你看到我在上面做了什么 - 只需将数组内容重建为字符串,然后将该字符串写入缓存文件。

但是,我相信有更好的方法,所以有人可以帮助我吗?

谢谢!xD

编辑:上面的方法也是一个问题,如果这个过程在完全相同的毫秒内发生多次 - 有些事情会搞砸,对吧?

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

file_put_contents能够将数据追加到文件末尾,请使用标志FILE_APPEND调用此方法(详细信息(。您可以将定义数组的方法更改为如下所示:

$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);

但是,如果您不能更改定义数组的方法traffic_array那么file_put_contents不适合您。使用带有标志"r+"的fopen(),使用 fseek() 将指针移动到正确的位置以将新数据放在文件中,fwrite()用于仅写入新数据,以及fclose()

// Content of file: <?php $a = array('k' => array(), 'k2' => array());'n
$f = fopen('file', 'r+');
fseek($f, -3, SEEK_END); // place the pointer after last value of array, before ");'n"; cont from end
fwrite($f, ", 'k3' => array('f'=>'a'));'n"); // put new data, also add overwrited data ");'n"
fclose($f);
//now content of file: <?php $a = array('k' => array(), 'k2' => array(), 'k3' => array('f'=>'a'));'n

更改输入文件可能会导致巨大的问题。

上面的方法还有一个问题,如果这个过程在完全相同的毫秒内发生多次 - 有些事情会搞砸,对吧?

对,阅读有关文件锁定的信息。

这似乎不是一种很好的缓存方式,仅仅是因为您必须问这个问题。添加新条目应该很容易。

我的建议是:

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

  2. 使用不包含 PHP 代码的文件,而是包含 CSV 等其他内容的文件,您可以在其中轻松附加到该文件,而不必担心关闭分号等,并且您还可以在需要时使用内置的 PHP 库函数(如 fgetcsv(((快速读取它。