Cha*_*app 2 php recursion loops multidimensional-array
我基本上想使用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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
这是错误的,会使您陷入无休止的循环:
$this->_replace_amp($post, $new_post);
Run Code Online (Sandbox Code Playgroud)
您无需将其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;
}
Run Code Online (Sandbox Code Playgroud)