Chapp
Chapp

Reputation: 287

Call str_replace() on all values while recursively traversing a multidimensional array

I basically want to use str_replace() all values of a multidimensional array. I can't seem to work out how I would do this for multidimensional arrays. I get a little stuck when the value is an array -- it just seems to be in a neverending loop. I'm new to PHP so examples 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;
}

Upvotes: 2

Views: 12954

Answers (2)

Cyclone
Cyclone

Reputation: 18295

...What's wrong with array_walk_recursive?

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

Upvotes: 3

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91932

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

Upvotes: 6

Related Questions