为什么我的递归数组搜索不能处理这个数据数组?
我有一个递归数组搜索函数,以前一直在工作。由于某种原因,现在它似乎告诉我数组中存在实际上不存在的东西。
IE,我有一个像这样的数组
Array
(
[0] => Array
(
[name] => people
[groups] => Array
(
[0] => Array
(
[name] => tom
)
[1] => Array
(
[name] => john
)
)
)
)
和我的递归搜索函数:
function searchArrayRecursive($needle, $haystack){
foreach ($haystack as $key => $arr) {
if(is_array($arr)) {
$ret=searchArrayRecursive($needle, $arr);
if($ret!=-1) return $key.','.$ret;
} else {
if($arr == $needle) return (string)$key;
}
}
return -1;
}
但是如果我要执行以下操作:
$search = searchArrayRecursive('kim',$the_array);
if($search != -1) {
echo 'result: found<br />';
} else {
echo 'result: not found';
}
我得到结果:找到 它显然不在数组中。也许我的功能从来没有发挥过作用。也许我的头朝后。有什么想法吗?
注意:当我搜索 tom 或 john oO 时,我也会得到结果:找到
I have a recursive array search function which has previously been working a treat. For some reason though now it appears to be telling me things exist in the array which actually don't.
IE, I have an array like this
Array
(
[0] => Array
(
[name] => people
[groups] => Array
(
[0] => Array
(
[name] => tom
)
[1] => Array
(
[name] => john
)
)
)
)
And my recursive search function:
function searchArrayRecursive($needle, $haystack){
foreach ($haystack as $key => $arr) {
if(is_array($arr)) {
$ret=searchArrayRecursive($needle, $arr);
if($ret!=-1) return $key.','.$ret;
} else {
if($arr == $needle) return (string)$key;
}
}
return -1;
}
If I were to do the following however:
$search = searchArrayRecursive('kim',$the_array);
if($search != -1) {
echo 'result: found<br />';
} else {
echo 'result: not found';
}
I get result: found
Its clearly not in the array. Maybe my function never worked. maybe my heads on backwards. Any ideass?
note: I also get result: found when I search for tom or john o.O
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该示例按提供的方式工作。也许您的实际数据有大小写混合? ('john' != 'John') 或者可能是额外的空格或杂散的换行符,因为它们在创建数组时没有被修剪?
尝试使用 var_dump() 而不是 print_r()。它应该向您显示您尝试搜索的数据的确切性质。我怀疑您的数据可能不是您期望的格式。
This example works as provided. Possibly your actual data has mixed case? ('john' != 'John') or possibly extra spaces or a stray newline because they weren't trimmed when the array was created?
Try a var_dump() instead of a print_r(). It should show you the exact nature of the data you are trying to search. I suspect your data may not be in the format you expect it to be.