如何在PHP中获取密钥的索引号?

时间:2013-06-21 05:49:07

标签: php arrays

我在PHP中有一个数组如下:

[0] => Array
    (
        [41] => 20
        [2] => 42
        [3] => 30
        [12] => 94
        [32] => -2
        [39] => -3
        [40] => -15
    )

我只想获取特定键的索引号,例如键41的索引号是0,键的索引号:2是{{1 }}, 等等。所以请告诉我如何用PHP完成它。感谢

3 个答案:

答案 0 :(得分:5)

快速方式

$number = array_search($index, array_keys($array));

很长的路

$i = 0;
$number = false;
foreach ($array as $key => $value){
if ($key == $index){
    $number = $i;
    break;}
$i++;
}

答案 1 :(得分:0)

如果内存使用量无可置疑,我将保留第二个数组来保存键索引关系。否则,您必须在数组中搜索指定的索引(使用foreach循环)。

答案 2 :(得分:0)

<?php
function multiarray_keys($ar)
{
   foreach($ar as $k => $v) 
  {
    $keys[] = $k;
    if (is_array($ar[$k]))
        $keys = array_merge($keys, multiarray_keys($ar[$k]));
  }
   return $keys;
}
?>

示例代码:

<?php
      $array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),"size"  => array("small", "medium", "large"));
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";

&GT;

Example output:

 Array
 ( 
    [color] => Array
    (
        [1stcolor] => blue
        [2ndcolor] => red
        [3rdcolor] => green
    )
    [size] => Array
    (
        [0] => small
        [1] => medium
        [2] => large
    )
 )
 Array
(
  [0] => color
  [1] => 1stcolor
  [2] => 2ndcolor
  [3] => 3rdcolor
  [4] => size
  [5] => 0
  [6] => 1
  [7] => 2
 )