将嵌套的PHP数组打印为$ var ['key'] ['key'] ['key'] = value; [英] Print nested PHP array as $var['key']['key']['key'] = value;

查看:78
本文介绍了将嵌套的PHP数组打印为$ var ['key'] ['key'] ['key'] = value;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要将某些设置(使用fwrite())以以下格式写入php文件:

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

为此具有嵌套的php数组

Have nested php array for this

代码将覆盖文件中上面定义的某些值,对我而言,Var_export()无用.

The code will override some values, defined above in the file, Var_export() useless in my case.

有什么好的解决方案吗?

Any nice solution?

推荐答案

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 );

这比Perl版本更简单,因为PHP仅具有一种数组类型,而无需担心标量引用.我还决定不尝试收集输出,而只是使用echo;您可以根据需要将其替换为fwrite(),或者仅使用输出缓冲将结果捕获为字符串.

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.请注意,尽管此函数的输出通常每个值包含一行,但这并不能保证:var_export()的输出可能包含换行符,这些换行符将传递给输出.我发现触发这种行为的两种情况包括带有换行符的数组键和空数组,由于某种原因,它们被导出为"array (\n)"而不是"array()".

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()".

这篇关于将嵌套的PHP数组打印为$ var ['key'] ['key'] ['key'] = value;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆