递归搜索数组中的键 [英] Search for a key in an array, recursively

查看:24
本文介绍了递归搜索数组中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private function find($needle, $haystack) {
    foreach ($haystack as $name => $file) {
        if ($needle == $name) {
            return $file;
        } else if(is_array($file)) { //is folder
            return $this->find($needle, $file); //file is the new haystack
        }               
    }

    return "did not find";
}

嘿,此方法在关联数组中搜索特定键并返回与其关联的值.递归有问题.有什么线索吗?

Hey, this method searches for a specific key in an associative array and returns the value associated with it. There's some problem with the recursion. Any clue?

推荐答案

也许这有点矫枉过正,但使用 RecursiveIterators 很有趣 :)

Maybe it's overkill, but it's funny to use RecursiveIterators :)

更新:也许旧版本的 PHP 有点过头了,但是对于 >=5.6(特别是 7.0)我会毫无疑问地完全使用它.

UPDATE: Maybe it was overkill with old versions of PHP, but with >=5.6 (specially with 7.0) I would totally use this without doubt.

function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            return $value;
        }
    }
}

更新:此外,从 PHP 5.6 开始,您可以使用生成器轻松迭代所有通过过滤器的元素,而不仅仅是第一个:

UPDATE: Also, as of PHP 5.6, with generators you can easily iterate over all elements which pass the filter, not only the first one:

function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            yield $value;
        }
    }
}

// Usage
foreach (recursiveFind($haystack, $needle) as $value) {
    // Use `$value` here
}

这篇关于递归搜索数组中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆