php - 多维数组的递归循环?

标签 php loops recursion multidimensional-array

我基本上想使用 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/

相关文章:

php - Jquery onload 重复结果

java - 使用 ArrayList 显示多个 vector 对象 Java

loops - 关于golang接口(interface)循环

python - 如何将这个迭代函数写成递归函数?

python - 创建没有重复的树

php - 使用 jQuery 或 JavaScript 替换损坏的图像

php - 如果服务器上的 PHP 版本是 5.2,我如何使用 mysqli->fetch_all

javascript - 如何清空数组?

python - 实现 group_by_owners 字典

python - python 中的 'yield' 关键字是如何真正起作用的,尤其是当它带有递归时?