我编写了晚编码,我注意到php在多维数组解析时做了一些意想不到的事情。据我所知,php 5.3从来没有这样做过,老实说,如果它这样做会更方便。我只是想知道我是不是疯了,可以使用深夜的理智检查。
这是&#39>正在进行的事情:
我有一个原始帖子,我正在解析成一个需要单维数组的函数。该函数使用foreach在数组中运行,并处理来自原始帖子的信息。
示例:
//Paranoid string muddling function
function punk($str) {
return (preg_replace('/[^a-z0-9]+/i', '_', $str) );
}
//Same thing as punk, but for simple arrays();
function punk_array($array=array()) {
if (count($array)) {
$out = array();
foreach ($array as $key => $row) {
$out[$key] = punk($row);
}
return $out;
}
return false;
}
用这个实例化它:
$this->post = punk_array($_POST);
但是,当我传递一个多维帖子时,我不必在函数内部做任何事情来使它处理数组的所有二级和三级级别。它就是这样做的。这非常出乎意料,可能会破坏我在5.3x上写下的一些内容。
这里是输出,它完美地模拟了我的$ _POST的输入结构,解析了所有内容,即使它不应该:
Array
(
[direct_deposit] => 0
[accept] => Array
(
[2] => on
[7195] => on
[4803] => on
[302] => on
[4203] => on
[402] => on
[502] => on
)
[withdrawal] => Array
(
[2] => This_is_a_red_cent_test
[6515] => 17e7LwQQKR4xh3doTwkbEoEj2RGWnkX6vd
[202] => This_is_a_red_cent_test
[102] => This_is_a_red_cent_test
[7195] => This_is_a_red_cent_test
[4803] => This_is_a_red_cent_test
[302] => This_is_a_red_cent_test
[4203] => This_is_a_red_cent_test
[402] => This_is_a_red_cent_test
[502] => This_is_a_red_cent_test
)
[default] => 6515
)
现在,我错误地认为为了使其与上面的数组结构一起工作,我应该在数组的每个级别进行循环,或者递归循环以实现相同的效果?
这是5.4中的新功能,还是一个bug?这是在任何地方记录的吗?
提前感谢您的时间和见解。
答案 0 :(得分:2)
引用preg_replace文档:
如果主题是数组,则执行搜索和替换 主题的每个条目,返回值也是一个数组。
这意味着punk_array
函数实际执行二维数组解析。第一级是调用foreach
的{{1}}循环,第二级是检测数组并在所有这些元素上运行其函数的实际punk
函数。
除非你把它作为一个递归函数,否则它不会在第三维上工作。这是你感到困惑的地方。
请参阅下面的代码和示例,请注意第三级没有得到朋克。
https://ideone.com/TZ7nCu 版本我运行它:5.4.4-12
preg_replace
Ideone的输出
//Paranoid string muddling function
function punk($str) {
return (preg_replace('/[^a-z0-9]+/i', '_', $str));
}
//Same thing as punk, but for simple arrays();
function punk_array($array=array()) {
if (count($array)) {
$out = array();
foreach ($array as $key => $row) {
$out[$key] = punk($row);
}
return $out;
}
return false;
}
$data = array(
'test' => 'hello world',
'test2' => 'foo bar wat',
'multi' => array(
'foo' => 'bar test',
'php' => 'value bla bla BLA aseuf4398',
'multi2' => array(
'test' => 'testing the third dimension'
)
)
);
print_r(punk_array($data));
希望这可以解决它。