我基本上想使用 str_replace 多维数组的所有值。我似乎无法弄清楚如何为多维数组执行此操作。当值是一个数组时,我有点卡住了,它似乎处于一个永无止境的循环中。我是 php 的新手,所以 emaples 会很有帮助。
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;
}
关于php - 多维数组的递归循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088687/