多维数组的递归循环? [英] Recursive loop for multidimenional arrays?

查看:340
本文介绍了多维数组的递归循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想使用str_replace多维数组的所有值.我似乎无法弄清楚如何对多维数组执行此操作.当值是一个数组时,似乎有点陷入永无止境的循环中,我有点卡住了.我是php的新手,所以特别有用.

I basically want to use str_replace all values of a multidimenional array. I cant seem to work out how I would do this for multidimenional arrays. I get a little stuck when the value is an array its just seems to be in a never ending loop. Im new to php so emaples would be helpful.

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 is wrong and will put you into a never-ending loop:

$this->_replace_amp($post, $new_post);

您不需要发送new_post作为参数,并且您还想针对每次递归使问题更小.将您的功能更改为以下内容:

You don't need to send new_post as an argument, and you also want to make the problem smaller for each recursion. Change your function to something like this:

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;
}

这篇关于多维数组的递归循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆