我使用以下函数递归搜索数组:
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语句能够执行它应该执行的操作,但是在函数调用时我没有输出。
答案 0 :(得分: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;
}
此功能将一直循环,直到找到您要查找的密钥。
答案 1 :(得分:4)
此外,您可以使用内置函数array_walk_recursive并提供回调。
答案 2 :(得分:2)
您必须返回找到的值,因此请更改:
search2($subarray, $key);
要:
return search2($subarray, $key);