PHP:从递归数组搜索函数返回 [英] PHP: Returning from a recursive array searching function

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

问题描述

所以我有这个(简单的)方法:

So I have this (simple) method:

/**
 * @param       $needle
 * @param       $haystack
 *
 * @return array
 */
public function recursiveArraySearch($needle, $haystack)
{
    $array = false;

    foreach ($haystack as $key => $value) {
        if ($key === $needle) {
            $array = $value;
        } elseif (is_array($value)) {
            $this->recursiveArraySearch($needle, $value);
        }
    }

    return $array;
}

是这样称呼的:<代码>$result = $this->recursiveArraySearch('some_index', $configArray);

它无法将它一劳永逸地返回到 $result`.

It am having trouble return it once and for all back to $result`.

如果 $needle$key 匹配,那么我只希望它返回值,但目前它正在返回自身.

If the $needle matches the $key then I just want it to return the value but at the moment it's returning to itself.

我还没有真正做过的事情.

Something I haven't actually done yet.

谢谢

更新:当我按照答案的建议返回该方法并且它到达数组节点的末尾(如二叉树搜索)时,它将一个字符串作为 $haystack 并因此返回 false.

UPDATE: When I return the method as the answers suggest and it reached the end of an array node (like a binary tree search) it passes a string in as the $haystack and thus return false.

数据结构:我可能想要获得红色圆圈键的值,或者我可能想要橙色圆圈键的值?

Data Structure: I may want to get the values of key circled red or I may want the values of the key circled orange?

函数需要返回false.

The function needs to return them of false.

推荐答案

public function recursiveArraySearch($needle, $haystack)
{
    foreach ($haystack as $key => $value) {
        if ($key === $needle) {
            return $value;
        } elseif (is_array($value)) {
            $result = $this->recursiveArraySearch($needle, $value);
            if ($result !== false){
                return $result;
            }
        }
    }

    return false;
}

当您向下递归时,您需要检查结果并仅在找到项目时返回.如果什么也没找到,那么你需要让循环继续.

When you recurse down you need to check the result and return only if an item was found. If nothing was found then you need to let the loop continue.

这假设您的数组不包含任何布尔值.如果是这样,您将需要使用替代方法来避免将 false 值混淆为未找到.

This assumes that your array does not contain any boolean values. If it does, you'll need to use an alternate method to avoid confusing a false value for not found.

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

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