0

当找到 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”来调整函数,但这也不起作用。

任何人都知道如何解决这个问题?

非常感谢!

4

2 回答 2

1

当你搜索2你会得到0,因为你有$haystack[0][score1] = 2。您需要指定您要查找的内容,userid而不是其他任何内容。

foreach($haystack as $key => $value) {
  if ($value['userid'] == $needle) {
    return $key;
  }
}
于 2012-05-30T17:06:38.060 回答
1

当我搜索 2(找不到)时,它返回 0。当然,这是不正确的......

查看您提供的数组,它正确的。该值2出现在 key 中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 */ }
于 2012-05-30T17:12:35.893 回答