search
Homephp教程php手册php中将数组存到文件里的实现代码

php的数组十分强大,有些数据不存入数据库直接写到文件上,用的时候直接require

第一次分享代码;(写得很烂..紧张纳紧张纳)
php的数组十分强大,有些数据不存入数据库直接写到文件上,用的时候直接require。
(实际中有用到把数组存在到文件中的功能,不过分享的代码跟实际应用中的有点不同)
代码如下:
function cacheArr(&$data){
if(!$data)throw new Exception('数组不能为空');
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;
}
?>
//存储数组
$hello=array(1=>'test',2=>array('hello123'));
cacheArr($hello);
unset($hello);
//读取数组
require 'hello.arr.php';
print_r($hello);
?>

测试的时候注意下变量问题。包括定义的全局变量
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools