65.9K
CodeProject 正在变化。 阅读更多。
Home

在 PHP 中递归搜索和删除多维数组中的值

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.45/5 (4投票s)

2011年12月24日

CPOL

1分钟阅读

viewsIcon

39115

downloadIcon

196

递归地搜索和移除 PHP 数组/多维数组中的值。

引言

最近我遇到了一种情况,需要搜索和移除一个动态生成的多维数组中的值,该数组的大小和长度各不相同。经过多次尝试和错误,我发现最好的解决方案是递归地循环遍历数组,找到并移除该值。

使用代码

假设我们想要从一个数组中移除所有包含“FirstValue”的元素,例如

$value = "FirstValue"; //value/element we want to remove

并且我们有以下多维数组

$array["First"] = "FirstValue";
$array["Second"] = "SecondValue";
$array["Third"]["First"] = "FirstValue";
$array["Third"]["Second"] = "SecondValue";
$array["Fourth"]["Third"]["First"] = "FirstValue";
$array["Fourth"]["Third"]["Second"] = "SecondValue";
$array["Fifth"]["Fourth"]["Third"]["First"] = "FirstValue";
$array["Fifth"]["Fourth"]["Third"]["Second"] = "SecondValue";

对上面的数组使用简单的 print_r($array),将打印以下内容

Array
(
    [First] => FirstValue
    [Second] => SecondValue
    [Third] => Array
        (
            [First] => FirstValue
            [Second] => SecondValue
        )

    [Fourth] => Array
        (
            [Third] => Array
                (
                    [First] => FirstValue
                    [Second] => SecondValue
                )

        )

    [Fifth] => Array
        (
            [Fourth] => Array
                (
                    [Third] => Array
                        (
                            [First] => FirstValue
                            [Second] => SecondValue
                        )

                )

        )
)

为了从这个多维数组中移除所有包含值“FirstValue”的元素,我们调用 recursiveRemoval($array, $value) 函数如下

recursiveRemoval($array, $value);

recursiveRemoval 函数的代码如下

function recursiveRemoval(&$array, $val)
{
    if(is_array($array))
    {
        foreach($array as $key=>&$arrayElement)
        {
            if(is_array($arrayElement))
            {
                recursiveRemoval($arrayElement, $val);
            }
            else
            {
                if($arrayElement == $val)
                {
                    unset($array[$key]);
                }
            }
        }
    }
}

首先,我们检查传递给函数的 array 是否实际上是一个数组。如果传递的 array 是一个数组,我们就遍历它的元素。如果该元素也是一个数组(我们的数组不是一维数组),我们就递归地再次调用函数 recursiveRemoval($arrayElement, $val),将多维数组分解成一维数组。

最后,我们处理一维数组的元素,并将它们与传递的 value 进行比较,我们想要移除该值,并 unset 数组的键($array[$key])。

结论

我在工作期间编写了这段代码,用于搜索和移除动态生成的多维数组中的元素。在许多情况下,递归可以救命,希望我的代码能在你遇到与我相同的情况时帮助到你。

© . All rights reserved.