【问题标题】:Recursive loop for multidimenional arrays?多维数组的递归循环?
【发布时间】:2011-08-30 15:05:12
【问题描述】:

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

谢谢

【问题讨论】:

  • 向我们展示您目前的想法。

标签: php loops recursion multidimensional-array


【解决方案1】:

这是错误的,会让你陷入永无止境的循环:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 因为在你的 eggsample 中如果你添加一个嵌套级别:$fruits = [ 'sweet' =&gt; $sweet, 'sour' =&gt; 'lemon', 'its_not' =&gt; ['recursive_depth'] ]; 在这种情况下你没有得到 'its_not' 的正确键 - 它给你 0,预期 its_not --或者正如有人所说此功能仅访问叶节点(php.net -- 哈哈,他把它大写了)
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2019-06-14
    • 2012-11-06
    • 2020-10-15
    • 2017-12-28
    • 2017-11-28
    相关资源
    最近更新 更多