如何在php中查找数组中索引的位置

时间:2012-08-22 06:08:22

标签: php arrays

我有一个像这样的数组

Array
(
[33] => 
[53] => 
[82] => 
[36] => 
[47] => 
[42] => 
[1] => 
[12] => 
[86] => 
[68] => 
[31] => 1.00
[2] => 1.00
[87] => 2.00
[50] => 3.00
[10] => 3.00
[55] => 3.00
[48] => 3.00
[70] => 3.00
[90] => 3.00
[37] => 3.00
[69] => 3.00
[8] => 3.00
[49] => 3.00
[26] => 3.00
[13] => 3.00
[61] => 3.00
[59] => 3.00
[73] => 4.00
[64] => 4.00
[77] => 4.00
[78] => 4.00
[65] => 4.00
[66] => 4.00
[63] => 4.00
[76] => 4.00
[51] => 4.00
[52] => 4.00
[43] => 4.00
[58] => 4.00
[60] => 4.00
[74] => 4.00
[67] => 4.00
[35] => 4.00
[17] => 4.00
[16] => 4.00
[18] => 4.00
[20] => 4.00
[41] => 4.00
[15] => 4.00
[11] => 4.00
[4] => 4.00
[5] => 4.00
[6] => 4.00
[7] => 4.00
[83] => 4.00
[22] => 4.00
[34] => 4.00
[38] => 4.00
[40] => 4.00
[25] => 4.00
[32] => 4.00
[80] => 4.00
[81] => 4.00
[27] => 4.00
[30] => 4.00
[79] => 5.00
[89] => 5.00
[88] => 5.00
[72] => 5.00
[71] => 5.00
[44] => 5.00
[21] => 5.00
[23] => 5.00
[24] => 5.00
[19] => 5.00
[14] => 5.00
[3] => 5.00
[9] => 5.00
[28] => 5.00
[29] => 5.00
[56] => 5.00
[57] => 5.00
[54] => 5.00
[46] => 5.00
[39] => 5.00
[45] => 5.00
[62] => 5.00
)

现在我想要找到特定索引的位置。即如果我搜索53,则返回其位置,即2。我在53位置考虑SECOND

4 个答案:

答案 0 :(得分:5)

使用array_keys()获取密钥,然后尝试使用array_search()获取它的索引。

$keys = array_keys($yourArray);
$key = array_search('53', $keys);

没有对它进行测试,但应该可以正常工作。

答案 1 :(得分:4)

你可以使用

$a = array_keys($array)

获取一个数组,其值为$ array =>钥匙

之后你可以使用

$a = array_flip($a);

使数组值是数组的索引(你想要的位置!

然后

$a["53"];//for example will get what you want 

希望有所帮助

注意:如果您经常使用我的方式访问$ a,因为它构建了数组,之后您将拥有O(1)访问时间,如果您需要一个或两个访问它更好,使用array_searcharray_keys数组中获取带有O(n)的索引。

答案 2 :(得分:2)

function findIndex($arr, $needle) {
    $i = 0;
    foreach ($arr as $key => $value) {
      if ($key === $needle) {
         return $i;
      }
      $i++;
    }
    return false;
}

答案 3 :(得分:1)

通过array_keys()函数获取所有数组键,然后提取所需的键值。 见http://www.php.net/manual/en/function.array-keys.php