Recursive loop for multidimenional arrays?

后端 未结 2 1070
说谎
说谎 2021-01-07 03:12

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

2条回答
  •  情歌与酒
    2021-01-07 04:02

    This is wrong and will put you into a never-ending loop:

    $this->_replace_amp($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;
    }
    

提交回复
热议问题