问题
Need to write (using fwrite()) some settings into php file in format:
$var['key']['key']['key'] = false; // bool
$var['key']['key'] = 'string'; // string
$var['key'] = 1; // numeric
Have nested php array for this
The code will override some values, defined above in the file, Var_export() useless in my case.
Any nice solution?
回答1:
I answered this question in Perl before — I guess I could just port the essentials of the answer to PHP:
function dump_array_recursive ( $prefix, $var ) {
if ( is_array( $var ) && !empty( $var ) ) {
foreach ($var as $key => $val) {
$prefix_key = $prefix . "[" . var_export( $key, true ) . "]";
dump_array_recursive( $prefix_key, $val );
}
} else {
echo "$prefix = " . var_export( $var, true ) . ";\n";
}
}
// example call:
dump_array_recursive( '$foo', $foo );
This is a little bit simpler than the Perl version, since PHP has only one array type and no scalar references to worry about. I also decided not to try collecting the output, but simply used echo
; you can replace it with fwrite()
if you want, or just use output buffering to catch the result in a string.
Ps. Note that, while the output of this function usually contains one line for each value, this is not guaranteed: the output of var_export()
might contain newlines, which will be passed to the output. Two cases which I've found to trigger such behavior include array keys with newlines in them and empty arrays, which for some reason are exported as "array (\n)"
instead of just "array()"
.
来源:https://stackoverflow.com/questions/8108972/print-nested-php-array-as-varkeykeykey-value