我使用過兩種辦法:
第一種是數組序列化,簡單,但是調用時比較麻煩一些;第二種是儲存為標準的數組格式,儲存時麻煩但是調用時簡單。
第一種方法:
PHP代碼
複製代碼 代碼如下:$file="./cache/file.cache";
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
//緩衝
file_put_contents($file,serialize($array));//寫入緩衝
//讀出緩衝
$handle = fopen($file, "r");
$cacheArray = unserialize(fread($handle, filesize ($file)));
第二種方法:
比較複雜,先貼幾個函數: 複製代碼 代碼如下://寫入
function cache_write($name, $var, $values) {
$cachefile = S_ROOT.'./data/data_'.$name.'.php';
$cachetext = "<?php\r\n".
"if(!defined('CHECK_CODE')) exit('Access Denied');\r\n".
'$'.$var.'='.arrayeval($values).
"\r\n?>";
if(!swritefile($cachefile, $cachetext)) {
exit("File: $cachefile write error.");
}
}
//數群組轉換成字串
function arrayeval($array, $level = 0) {
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "\t";
}
$evaluate = "Array\n$space(\n";
$comma = $space;
foreach($array as $key => $val) {
$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
$val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
} else {
$evaluate .= "$comma$key => $val";
}
$comma = ",\n$space";
}
$evaluate .= "\n$space)";
return $evaluate;
}
//寫入檔案
function swritefile($filename, $writetext, $openmod='w') {
if(@$fp = fopen($filename, $openmod)) {
flock($fp, 2);
fwrite($fp, $writetext);
fclose($fp);
return true;
} else {
runlog('error', "File: $filename write error.");
return false;
}
}
調用方法很簡單:
PHP代碼 複製代碼 代碼如下:cache_write('file', 'arrayName', $array);
使用上形同標準的include格式:
PHP代碼 複製代碼 代碼如下:@include ('./data/data_cache.php');
//數組重新排序
sort($arrayName);