我创建了一个递归函数来查找多维数组中的键值
功能:
public function find_key_recursive($haystack, $needle) {
foreach($haystack as $key=>$value) {
if(is_array($value)){
$this->find_key_recursive($value, $needle);
} else if($key === $needle) {
return $value;
}
}
}
(部分)数组:
$oLayoutProperties =
Array
(
[header] => Array
(
[logo_float] => left
[logo_upload] => http://placehold.it/150x100&text=afbeelding
[logo_margin_top] => 0
[searchbar_toggle] => false
[language_toggle] => false
[color] => 0
[font_size] => 12
[background_color] => 0
)
[menu] => Array
(
[menu_type] => full
[menu_align] => left
[menu_position_toggle] => false
[menuheight] => Array
(
[bar_height] => 0
)
[color] => 0
[font_size] => 12
[text_transform] => like_pagetitle
[background_color_hover] => 0
[color_hover] => 0
)
[submenu] => Array
(
[color] => 0
[font-size] => 12
[item_height] => 0
[item_width] => 0
[text-transform] => like_pagetitle
[background_color] => 0
[background_color_hover] => 0
[color_hover] => 0
)
)
我调用函数如下:
$oElement_controller->find_key_recursive($oLayoutProperties, 'logo_float');
我验证(使用 echo )确实找到了键“logo_float”,但我似乎无法取消递归函数?
我尝试了以下方法:
- 返回错误;
- 休息;
以上似乎都不起作用。 如何停止递归函数?
最佳答案
您可以使用static
变量来记住多个函数调用之间的状态。它使函数在多次调用之间记住给定变量(本例中的 $needle_value
)的值。
public function find_key_recursive($haystack, $needle){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key=>$value) {
if(is_array($value)){
$this->find_key_recursive($value, $needle);
} else if($key === $needle) {
$needle_value = $value;
return $needle_value;
}
}
}
此函数最终返回 $needle_value
,这是大海捞针。
关于php - 递归函数不停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34137679/