当找到 userid 的值时,我使用此函数搜索(最高)数组键:
function array_search_value($needle,$haystack) {
foreach($haystack as $key => $value) {
if(in_array($needle, $value)) return $key;
}
}
我的数组看起来像这样(它是由一个简单的查询生成的):
Array
(
[0] => Array
(
[0] => 1
[userid] => 1
[1] => 2
[score1] => 2
[2] => 0
[score2] => 0
)
[1] => Array
(
[0] => 3
[userid] => 3
[1] => 2
[score1] => 2
[2] => 2
[score2] => 2
)
[2] => Array
(
[0] => 4
[userid] => 4
[1] => 1
[score1] => 1
[2] => 1
[score2] => 1
)
[3] =>
)
此代码:
echo array_search_value(4, $r)
返回 2,这是正确的。
查找 1 得到 0,这是正确的。
但是,当我搜索 2(找不到)时,它返回 0。当然,这是不正确的...我希望它做的是根本不返回任何内容,而不是 0。我尝试通过添加"== true"来调整函数,但这也不起作用。
有人知道如何解决这个问题吗?
多谢!
当我搜索 2(找不到)时,它返回 0。当然,这是不正确的...
查看您提供的数组,这是正确的。2
值显示在键0
中:
[0] => Array
(
[0] => 1
[userid] => 1
[1] => 2 // here
[score1] => 2 // and here
[2] => 0
[score2] => 0
)
如果您只想查看userid
键,那么您不能只使用 in_array()
,而必须这样做:
<?php
function array_search_value($needle,$haystack) {
foreach($haystack as $key => $value) {
if($value['userid'] === $needle) return $key;
}
return null; // not found
}
if (array_search_value(2, $r) === null) { /* doesn't happen */ }
当您搜索2
时,您将获得0
,因为您有$haystack[0][score1] = 2
。您需要指定您要查找userid
而不是其他任何内容。
foreach($haystack as $key => $value) {
if ($value['userid'] == $needle) {
return $key;
}
}