PHP:通用递归数组搜索

str*_*opf 1 php arrays recursion

我尝试在数组中找到一个值,无论该数组有多深或它可能具有什么"结构".但我的方法并没有找到所有的价值观.我想我的递归错了,但我不知道.

$haystack = array(
        'A',
        'B' => array('BA'),
        'C' => array('CA' => array('CAA')),
        'D' => array('DA' => array('DAA' => array('DAAA')))
    );

function array_find($needle, array $haystack) {
    foreach ($haystack as $value) {
        if (is_array($value)) {
            if (in_array($needle, $value)) {
                return true;
            } else {
                return array_find($needle, $value);
            }
        } else {
            if ($value == $needle) {
                return true;
            }
        }
    }
    return false;
}

$find = array('A', 'BA', 'CAA', 'DAAA');

foreach($find as $needle) {
    if (array_find($needle, $haystack)) {
        echo $needle, " found".PHP_EOL;
    } else {
        echo $needle, " not found".PHP_EOL;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*sov 7

只需将您的代码更改为:

function array_find($needle, array $haystack) {
    foreach ($haystack as $value) {
        if (is_array($value)) {
            if (in_array($needle, $value)) {
                return true;
            } else {
                if (array_find($needle, $value)) {
                    return true;
                }
            }
        } else {
            if ($value == $needle) {
                return true;
            }
        }
    }   
    return false;
}
Run Code Online (Sandbox Code Playgroud)

问题出在你的退货声明中.