[英]Find key in nested associative array
前几天我问了一个与此相关的问题,我得到了一个答案,但它没有做我想要的。 这是我遍历多维关联数组的方法,检查一个键是否在数组中(从我之前的问题的答案):
private function checkKeyIsInArray($dataItemName, $array)
{
foreach ($array as $key => $value)
{
// convert $key to string to prevent key type convertion
echo '<pre>The key: '.(string) $key.'</pre>';
if ((string)$key == $dataItemName)
return true;
if (is_array($value))
return $this->checkKeyIsInArray($dataItemName, $value);
}
return false;
}
这是我的数组结构:
Array (
[0] => Array ( [reset_time] => 2013-12-11 22:24:25 )
[1] => Array ( [email] => someone@example.com )
)
该方法遍历第一个数组分支,但不遍历第二个。 有人可以解释为什么会出现这种情况吗? 好像我错过了什么。
问题是无论递归调用是否成功,都会返回递归调用返回的内容。 只有在递归期间找到密钥时才应该返回,否则你应该继续循环。
private function checkKeyIsInArray($dataItemName, $array)
{
foreach ($array as $key => $value)
{
// convert $key to string to prevent key type convertion
echo '<pre>The key: '.(string) $key.'</pre>';
if ((string)$key == $dataItemName)
return true;
if (is_array($value) && $this->checkKeyIsInArray($dataItemName, $value))
return true;
}
return false;
}
顺便说一下,为什么这是一个非静态函数? 它似乎不需要任何实例属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.