Recursive cycle for multidimensional matrices?

Basically I want to use str_replace all the values ​​of a multidimensional element. I can't seem to figure out how to do this for multi-dimensional systems. I get a little stuck when the value is an array that seems to be in an infinite loop. Im new for 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;
}

thank

+2
source share
2 answers

This is wrong and will lead you into an endless loop:

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

You do not need to send new_postas an argument, and you also want to reduce the problem for each recursion. Change your function 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;
}
+4
source

... 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');
?>
+3

Source: https://habr.com/ru/post/1664766/


All Articles