Home  >  Article  >  Backend Development  >  Implementation code for saving arrays to files in PHP_PHP Tutorial

Implementation code for saving arrays to files in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:21:32809browse

This is my first time to share code; (poorly written.. nervous and nervous)
PHP arrays are very powerful. Some data are written directly to files without being stored in the database, and require directly when used.
(In practice, the function of saving arrays into files is useful, but the code shared is a bit different from the actual application)

Copy code Code As follows:

function cacheArr(&$data){
if(!$data)throw new Exception('Array cannot be empty');
foreach($GLOBALS as $key=>$value){
$str=$GLOBALS[$key];
$GLOBALS[$key]='changed';
if($data== 'changed'){
$strName=$key;
break;
}
$GLOBALS[$key]=$str;
}
ob_clean();
ob_start();
echo "function echoArr($arr,$arrName){
$arrCount=count($arr);$i==0;
foreach ($arr as $key=>$value){
++$i;
if(is_array($value)){
echo "n".(is_numeric($key)?$key :'''.$key.''').'=>array(';
echoArr($value,$arrName.(is_numeric($key)?'['.$key.']': '[''.$key.'']'));
if($i!=$arrCount)echo '),';
else echo ')';
continue;
}
if($i!=$arrCount)echo ((is_numeric($key))?$key:'''.$key.''').'=>'.(is_numeric($value) ?$value:'''.$value.''').',';
else echo ((is_numeric($key))?$key:'''.$key.''').' =>'.(is_numeric($value)?$value:'''.$value.''');
}
}
echo '$'.$strName.'=array( ';
echoArr($data,'');
echo ');';
echo "n?>";
$file=fopen($strName.'.arr.php ','w');
fwrite($file,ob_get_contents());
fclose($file);
ob_clean();
return true;
}
? >
//Storage array
$hello=array(1=>'test',2=>array('hello123'));
cacheArr($ hello);
unset($hello);
//Read array
require 'hello.arr.php';
print_r($hello);
?>

Pay attention to variables when testing. Includes defined global variables

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324909.htmlTechArticle Sharing code for the first time; (poorly written... nervous and nervous) PHP arrays are very powerful, Some data is written directly to the file without being stored in the database, and is directly required when used. (In practice...
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