我基本上想使用
str_replace()
多维数组的所有值。我似乎无法弄清楚如何对多维数组执行此操作。当值是一个数组时,我有点卡住了——它似乎处于一个永无休止的循环中。我是 PHP 新手,所以示例会很有帮助。
function _replace_amp($post = array(), $new_post = array())
{
foreach($post as $key => $value)
{
if (is_array($value))
{
unset($post[$key]);
$this->_replace_amp($post, $new_post);
}
else
{
// Replace :amp; for & as the & would split into different vars.
$new_post[$key] = str_replace(':amp;', '&', $value);
unset($post[$key]);
}
}
return $new_post;
}
这是错误的,会让你陷入永无休止的循环:
$this->_replace_amp($post, $new_post);
您不需要发送
new_post
作为参数,并且您还希望每次递归时使问题更小。将您的函数更改为如下所示:
function _replace_amp($post = array())
{
$new_post = array();
foreach($post as $key => $value)
{
if (is_array($value))
{
unset($post[$key]);
$new_post[$key] = $this->_replace_amp($value);
}
else
{
// Replace :amp; for & as the & would split into different vars.
$new_post[$key] = str_replace(':amp;', '&', $value);
unset($post[$key]);
}
}
return $new_post;
}
...array_walk_recursive有什么问题?
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>