Home > Backend Development > PHP Tutorial > php下把数组保存为文件格式的实例应用_php技巧

php下把数组保存为文件格式的实例应用_php技巧

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-17 09:28:06
Original
995 people have browsed it
我使用过两种办法:
第一种是数组序列化,简单,但是调用时比较麻烦一些;第二种是保存为标准的数组格式,保存时麻烦但是调用时简单。
第一种方法:
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 = ""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 $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);
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template