I have used two methods:
The first is array serialization, which is simple, but it is more difficult to call. The second is to save the data as a standard array format, which is difficult to save but simple to call.
Method 1:
PHP code
Copy codeThe 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 the cache
$ Handle = fopen ($ file, "r ");
$ CacheArray = unserialize (fread ($ handle, filesize ($ file )));
Method 2:
Complex: first, add a few functions:
Copy codeThe Code is as follows:
// Write
Function cache_write ($ name, $ var, $ values ){
$ Cachefile = S_ROOT. './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 .");
}
}
// Convert an array to a string
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;
}
// Write a 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 call method is simple:
PHP code
Copy codeThe Code is as follows:
Cache_write ('file', 'arrayname', $ array );
Use the same standard include format:
PHP code
Copy codeThe Code is as follows:
@ Include ('./data/data_cache.php ');
// Sorts the array again.
Sort ($ arrayName );