Home  >  Article  >  Backend Development  >  Example application of saving arrays in file format under PHP_PHP Tutorial

Example application of saving arrays in file format under PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:41:33890browse

I have used two methods:
The first is array serialization, which is simple, but more troublesome when calling; the second is to save it in a standard array format, which is troublesome when saving but troublesome when calling. Simple.
First method:
PHP code

Copy code The code is as follows:

$file=". /cache/file.cache";
$array = array("color" => array("blue", "red", "green"),
"size" => array("small ", "medium", "large"));
//Cache
file_put_contents($file,serialize($array));//Write cache
//Read cache
$ handle = fopen($file, "r");
$cacheArray = unserialize(fread($handle, filesize ($file)));

Second method:
It’s more complicated. Let’s post a few functions first:
Copy code The code is as follows:

//Write
function cache_write ($name, $var, $values) {
$cachefile = S_ROOT.'./data/data_'.$name.'.php';
$cachetext = ""if(!defined('CHECK_CODE')) exit('Access Denied');rn".
'$'.$var.'='.arrayeval($values).
"rn?> ;";
if(!swritefile($cachefile, $cachetext)) {
exit("File: $cachefile write error.");
}
}
//Array conversion into a string
function arrayeval($array, $level = 0) {
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "t";
}
$evaluate = "Arrayn$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;
}
//Write file
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;
}
}

The calling method is very Simple:
PHP code
Copy code The code is as follows:

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

Use the standard include format:
PHP code
Copy code The code is as follows:

@include ('./data/data_cache.php');
//Array reordering
sort($arrayName);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321137.htmlTechArticleI have used two methods: The first is array serialization, which is simple, but more troublesome when calling; The second is to save it in a standard array format, which is troublesome to save but easy to call...
Statement:
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