2

我正在使用以下函数递归搜索数组:

function search2($array, $key){
    if( array_key_exists($key, $array) ){
        print("<br> ----------------- FOUND <u>{$key}</u> with value: {$array[$key]}");

        return array( $key => $array[$key] );

    }else if( !array_key_exists($key, $array) ){
        foreach ($array as $index   =>  $subarray){
                if( is_array($subarray) ){
                    print("<br> ************* <u>{$index}</u> is an ARRAY");
                    print("<br> ************* RE-SEACHING <u>{$index}</u> FOR : <u>{$key}</u>");
                    search2($subarray, $key);
                }
        }
    }
}

因此,使用以下数组结构:

Array
(
    [personal] => Array
        (
            [title] => 
            [forename] => 
            [surname] => 
            [post_code] => 
            [date_of_birth] => Array
                (
                    [month] => 
                    [day] => 
                    [year] => 
                )

            [email_address] => email1@test.org
            [confirm_email_address] => 
            [mobile_telephone] => 
            [home_telephone] => 
            [work_telephone] => 
            [are_you_entering_fundraising_in_a_team] => Array
                (
                    [yes] => 0
                )

            [how_many_places_would_you_like] => 
            [team_name] => 
            [names_of_team_members] => 
            [how_did_you_hear_about_this_event] => 
            [please_tell_us_] => 
            [would_you_be_happy_for_publicity] => 
            [is_this_the_first_time_you_have_taken_part_in_or_attended_this_event] => Array
                (
                    [yes] => 0
                )

            [do_you_have_a_special_reason_for_taking_part_in_or_attending_this_event] => 
            [what_are_your_plans_for_raising_the_minimum_sponsorship_amount___please_be_as_detailed_as_possible] => 
            [number_of_tickets_required] => 1
        )
)

我的函数将继续调用自身,直到找到我正在搜索的索引。如果我正在搜索email_address,如果该数组键存在,则 if 语句的第一部分应返回该索引的值,否则它将在代码的第二部分进入递归模式。

问题是代码似乎可以工作,因为我得到了我的“找到”打印输出语句,如下所示:

print("<br> ----------------- FOUND <u>{$key}</u> with value: {$array[$key]}");

但是,我希望 return 语句能做它应该做的事情,但在我的函数调用点我没有得到任何输出。

4

3 回答 3

4

在数组函数中使用递归:

function in_array_r ( $needle, $haystack, $strict = true )
    {
        foreach ( $haystack as $value )
        {
            if (( $strict ? $value === $needle : $value == $needle ) || ( is_array ( $value ) && in_array_r ( $needle, $value, $strict )))
            {
                return true;
            }
        }

        return false;
    }

此函数将继续循环,直到找到您要查找的密钥。

于 2012-09-25T12:54:08.590 回答
4

您也可以使用带有回调的内置函数array_walk_recursive 。

于 2012-09-25T12:55:40.993 回答
2

你必须返回你找到的值,所以改变:

search2($subarray, $key);

到:

return search2($subarray, $key);
于 2012-09-25T12:53:50.883 回答