欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php下把數(shù)組保存為文件格式的實(shí)例應(yīng)用

 更新時(shí)間:2010年02月08日 08:43:59   作者:  
我們通常把一些常用的數(shù)據(jù)保存為數(shù)組格式方便調(diào)用,同時(shí)這也是緩存的重要方法。
我使用過(guò)兩種辦法:
第一種是數(shù)組序列化,簡(jiǎn)單,但是調(diào)用時(shí)比較麻煩一些;第二種是保存為標(biāo)準(zhǔn)的數(shù)組格式,保存時(shí)麻煩但是調(diào)用時(shí)簡(jiǎn)單。
第一種方法:
PHP代碼
復(fù)制代碼 代碼如下:

$file="./cache/file.cache";
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
//緩存
file_put_contents($file,serialize($array));//寫(xiě)入緩存
//讀出緩存
$handle = fopen($file, "r");
$cacheArray = unserialize(fread($handle, filesize ($file)));

第二種方法:
比較復(fù)雜,先貼幾個(gè)函數(shù):
復(fù)制代碼 代碼如下:

//寫(xiě)入
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.");
}
}
//數(shù)組轉(zhuǎn)換成字串
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;
}
//寫(xiě)入文件
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;
}
}

調(diào)用方法很簡(jiǎn)單:
PHP代碼
復(fù)制代碼 代碼如下:

cache_write('file', 'arrayName', $array);

使用上形同標(biāo)準(zhǔn)的include格式:
PHP代碼
復(fù)制代碼 代碼如下:

@include ('./data/data_cache.php');
//數(shù)組重新排序
sort($arrayName);

相關(guān)文章

最新評(píng)論