按值搜索时返回数组的索引

时间:2016-04-13 15:36:35

标签: php mysql arrays algorithm

我有MySQL结果的数组。我希望能够按值搜索并获取数组中的索引位置。

我的数组$array_result在下面给出

Array (
    [0] => Array ( [scores] => 90 ) 
    [1] => Array ( [scores] => 80 ) 
    [2] => Array ( [scores] => 73 )
    [3] => Array ( [scores] => 0 ) 
    [4] => Array ( [scores] => 0 ) 
    [5] => Array ( [scores] => 0 ) 
    [6] => Array ( [scores] => 0 ) 
    [7] => Array ( [scores] => 0 ) 
    [8] => Array ( [scores] => 0 ) 
    [9] => Array ( [scores] => 0 ) 
    [10] => Array ( [scores] => 0 ) 
    [11] => Array ( [scores] => 0 ) 
    [12] => Array ( [scores] => 0 ) 
    [13] => Array ( [scores] => 0 ) 
    [14] => Array ( [scores] => 0 ) 
    [15] => Array ( [scores] => 0 ) 
    [16] => Array ( [scores] => 0 ) 
    [17] => Array ( [scores] => 0 )
)

示例:我想搜索80并获取1的索引。我尝试过这个功能,但没有得到正确的回复:array_search(80, $array_result)

1 个答案:

答案 0 :(得分:0)

使用foreach循环来实现此目的。 Online link,试试这个。您首先匹配将返回索引。

<强>阵列

$array_result = array( 
    array ("scores" => 90 ), 
    array ("scores" => 80 ), 
    array ("scores" => 73 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ), 
    array ("scores" => 0 ) 
);

foreach($array_result as $key => $val){
    if(in_array(80, $val)){
        $out = $key;
        break;
    }       
}

echo $out;

<强>输出

  

1