我创建了一个递归函数来在多维数组中查找键值
功能:
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"确实找到了,但我似乎无法取消递归函数?
我尝试了以下方法:
- return false
- 断裂
以上这些似乎都不起作用。如何停止递归函数?
您可以使用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
,这是您想要的大海捞针。
public function find_key_recursive($haystack, $needle) {
foreach($haystack as $key=>$value) {
if(is_array($value)){
var $found = $this->find_key_recursive($value, $needle);
if ($found){
return $found;
}
} else if($key === $needle) {
return $value;
}
}
return false;
}
我已经有一段时间没有接触PHP了,但像这样的东西可能会起作用。
您可以将结果放入通过引用传递的变量中,如下所示:
public function find_key_recursive($haystack, $needle, &$found) {
foreach($haystack as $key => $value) {
if (is_array($value)) {
$this->find_key_recursive($value, $needle, $found);
} else if($key === $needle) {
$found = $value;
return;
}
}
}
$found = false;
$oElement_controller->find_key_recursive($oLayoutProperties, 'logo_float', $found);
if ($found !== false) {
// found!
}