php缓存数组到文件

时间:2022-02-27 12:17:40

php缓存数组到文件

static function getIDs($kemuid)
{
$cachefile="cache/" . $kemuid . ".cache";
$datas=array();
if (!file_exists($cachefile)||time() > (filemtime($cachefile) + 14400))
//缓存不存在或超过4小时
{
global $data;
//读取 id 集
$query="SELECT sid FROM shiti WHERE skemu = " . intval($kemuid);
$res = $data->query($query);
while($r = $data->fetchArray($res))
{
$datas[]=$r['sid'];
}
//写入缓存
file_put_contents($cachefile,serialize($datas));
/*
$fp= fopen($cachefile, "w");
fwrite($fp, serialize($datas));
fclose($fp); */
}
else
{
//读出缓存
$fp = fopen($cachefile,'r');//读
$datas = unserialize(fread($fp,filesize($cachefile)));//反序列化,并赋值
}
return $datas;
}