// 将array变成字符串, 来自discuz!
function arrayeval($array, $level = 0) {
if (! is_array ( $array )) {
return "\"$array\"";
}
$space = "";
for($i = 0; $i <= $level; $i ++) {
$space .= "\t";
}
$evaluate = "Array\n$space(\n";
$comma = $space;
if (is_array ( $array )) {
foreach ( $array as $key => $val ) {
$key = is_string ( $key ) ? "\"" . addcslashes ( $key, "\"\\" ) . "\"" : $key;
$val = ! is_array ( $val ) && (! preg_match ( "/^\-?[1-9]\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;
}
$test_array = array (
"6b" => "a\\",
"b",
"c",
array (
"c",
"d"
)
);
$fileAndVarName = "newFile";
// 在生成$encode_str的时候,为使字符串中原有字符格式不变,系统在编译时会给字符串中预定义字符前加 \ 使预定义字符保留在字符串中,但输出或打印字符串的时候只会输出打印出预定义字符,不会打印出预定义字符前面的 \
$encode_str = json_encode ( $test_array );
// 因为这里要把字符串打印成PHP代码,输出的时候,字符串中预定义字符会打乱程序运行,所以要在原有转义字符前再加转移字符,使字符串输出打印时在预定义字符前转义字符也能输出
$addslashes_str = addslashes ( $encode_str ); // addslashes将字符串中预定义字符前加 \ 使其能存放在字符串中不产生作用,不参与程序运行
echo stripslashes($addslashes_str); // 反转义函数,可去掉字符串中的反斜线字符。若是连续二个反斜线,则去掉一个,留下一个。若只有一个反斜线,就直接去掉。
echo "
";
// You can pass an array object or a string converted into json, which needs to be converted into an array when used.
set_cache ( "$fileAndVarName", $addslashes_str );
var_dump ( $addslashes_str );
echo "
";
include_once "./cache/$fileAndVarName.php";
var_dump ( $$fileAndVarName );
echo "
";
$decode_arr = ( array ) json_decode ( $$fileAndVarName );
var_dump ( $decode_arr );
echo "
";
// Another method of caching, use serialize to convert the array serial number into a string, store it in a file with any extension, use fopen to open it to read the string content, and then use unserialize to deserialize it into the original data
$serialize_str = serialize ( $test_array );
echo $serialize_str; // This is the array described but here it is just a string
echo "
";
$unserialize_str = unserialize ( $serialize_str ); // Restore the described data
var_dump($unserialize_str); // Restore to $test_array, the array structure is not lost.
?>