php array_search()不返回密钥

时间:2012-05-15 12:21:18

标签: php arrays

我有以下数组($ arrayres)(示例数据)

Array
(
[0] => Array
        (
            [description] => somedata
            [amount] => 52,6
            [b_id] => Array
                (
                    [0] => 138950106
                    [1] => 138950106
                )

        )

    [1] => Array
        (
            [description] => somedata 
            [amount] => 4,9
            [b_id] => Array
                (
                    [0] => 138911857
                    [1] => 138911857
                )

        )
)

然后我有一个查询,它也会在结果中返回b_id。我需要找到数组中包含哪些b_id以及它们在数组中的相应位置。所以我执行了一个array_rearch

while ($dbres = $res->fetchRow(MDB2_FETCHMODE_ASSOC))
{

    $key = array_search($dbres['b_id'], $arrayres);
    if ($key)
    {
        $keys[] = $key;
    }

}

但似乎没有匹配。 print_r($ keys)总是为空,尽管有些结果包含有问题的b_id。

我做错了什么?

3 个答案:

答案 0 :(得分:2)

当您执行array_search($dbres['b_id'], $arrayres);时,您正在搜索该嵌套数组的“第一层”上的键,当然,只有01作为键

你可以做那样的事情

for($i=0;$i<count($arrayres);$i++) {
    array_search($dbres['b_id'], $arrayres[$i]['b_id']);
    if ($key)
    {
     $keys[] = $key; /* just follow your logic */
    }
}

并且必须插入while循环

答案 1 :(得分:1)

您正在搜索的数组不包含您要搜索的b_id。它包含一个包含该出价的数组。

所以你需要循环遍历你拥有的数据数组,或者如果可以的话,为整个数组提供array_search。一种方法是:

function has_bid($arrayres, $bid) {
    foreach ($arrayres as $k => $v) {
            // This is assuming $bid is an array with 2 integers.
            if ($v['bid'] == $bid) {
                return $k;
            }
            // And this is assuming $bid is one of the integers.
            /*
               Here, array_search will search for the integer in an array that contains
               the values you are searching for in the first level,
               not inside an array that is inside another one.
               You can think of it as array_search searching the first level of it.
            */
            if (array_search($bid, $v) !== false) {
                return $k;
            }
    }
    return false;
}

你会像这样使用这个函数:

$key = has_bid($arrayres, $dbres['bid']);
if ($key !== false) {
     // do something...
}

答案 2 :(得分:-1)

试试这个......

if($key !== false){
     $keys[] = $key;
}
相关问题