递归地搜索数组中的键

Mar*_*man 20 php arrays recursion search

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";
}
Run Code Online (Sandbox Code Playgroud)

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

xPh*_*eRe 40

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

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

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这救了我.如果您不需要对密钥进行严格比较,请记住将`===`更改为`==`. (5认同)

Hai*_*vgi 16

function array_search_key( $needle_key, $array ) {
  foreach($array AS $key=>$value){
    if($key == $needle_key) return $value;
    if(is_array($value)){
      if( ($result = array_search_key($needle_key,$value)) !== false)
        return $result;
    }
  }
  return false;
} 
Run Code Online (Sandbox Code Playgroud)

这会奏效!

你需要停止递归深度搜索,返回false然后在函数中检查它.

您可以在此链接中找到更多函数示例(如使用RecursiveArrayIterator等):http: //php.net/manual/en/function.array-search.php


小智 6

xPheRe 提供的答案非常有帮助,但并没有完全解决我的实现中的问题。我们的数据结构中有多个嵌套的关联数组,并且任何给定的键都可能多次出现。

为了满足我们的目的,我需要实现一个在遍历整个结构时更新的持有者数组,而不是在第一次匹配时返回。真正的作品是由另一张海报提供的,但我想说声谢谢并分享我必须涵盖的最后一步。

public function recursiveFind(array $array, $needle)
{
    $iterator  = new RecursiveArrayIterator($array);
    $recursive = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
    $aHitList = array();
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            array_push($aHitList, $value);
        }
    }
    return $aHitList;
}
Run Code Online (Sandbox Code Playgroud)