php - 获取关联数组的数字索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3365766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:29:01  来源:igfitidea点击:

php - get numeric index of associative array

phparrays

提问by n00b

I have an associative array and I need to find the numeric position of a key. I could loop through the array manually to find it, but is there a better way build into PHP?

我有一个关联数组,我需要找到一个键的数字位置。我可以手动遍历数组以找到它,但是有没有更好的方法构建到 PHP 中?

$a = array(
  'blue'   => 'nice',
  'car'    => 'fast',
  'number' => 'none'
);

// echo (find numeric index of $a['car']); // output: 1

回答by Fosco

echo array_search("car",array_keys($a));

回答by quantumSoup

回答by Asterión


  $a = array(
      'blue' => 'nice',
      'car' => 'fast',
      'number' => 'none'
  );  
var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));

回答by Andrey Vorobyev

function arrayValuePosition($value, $array)
{
    return array_search($value, array_keys($array));
}

回答by Xriuk

While Fosco's answer is not wrong there is a case to be consideredwith this one: mixed arrays. Imagine I have an array like this:

虽然 Fosco 的回答没有错,但有一个需要考虑情况:混合阵列。想象一下,我有一个这样的数组:

$a = array(
  "nice",
  "car" => "fast",
  "none"
);

Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0which is wrongfor me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers(and this is kinda stupid in my opinion), so when array_search()searches for the index it stops at the first one because apparently ("car" == 0)is true.
Setting array_search()to strict mode won't solve the problem because then array_search("0", array_keys($a))would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys()to strings and then compares them correctly:

现在,PHP 允许这种语法,但它有一个问题:如果我运行 Fosco 的代码,我会发现0对我来说是错误的,但为什么会发生这种情况?
因为在字符串和整数之间进行比较时,PHP 会将字符串转换为整数(在我看来这有点愚蠢),所以当array_search()搜索索引时,它会停在第一个索引处,因为显然("car" == 0)是 true
设置array_search()为严格模式不会解决问题,因为array_search("0", array_keys($a))即使存在索引为 0 的元素,也会返回 false。
所以我的解决方案只是将所有索引从转换array_keys()为字符串,然后正确比较它们:

echo array_search("car", array_map("strval", array_keys($a)));

Prints 1, which is correct.

打印1,这是正确的。

EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:

编辑:
正如肖恩在下面的评论中指出的那样,同样的事情适用于索引值,如果你碰巧搜索这样的 int 索引:

$a = array(
  "foo" => "bar",
  "nice",
  "car" => "fast",
  "none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));

You will always get 0, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:

您总是会得到0,这是错误的,因此解决方案是将索引(如果您使用变量)转换为这样的字符串:

$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));

回答by MrBlc

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

所有基于 array_keys 的解决方案都不适用于混合数组。解决方法很简单:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

来自 php.net:如果第三个参数 strict 设置为 TRUE,则 array_search() 函数将在 haystack 中搜索相同的元素。这意味着它也会对大海捞针进行严格的类型比较,并且对象必须是同一个实例。

回答by n00b

a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:

我想出了一个解决方案……与 Fosco 的解决方案相比,可能效率很低:

 protected function getFirstPosition(array$array, $content, $key = true) {

  $index = 0;
  if ($key) {
   foreach ($array as $key => $value) {
    if ($key == $content) {
     return $index;
    }
    $index++;
   }
  } else {
   foreach ($array as $key => $value) {
    if ($value == $content) {
     return $index;
    }
    $index++;
   }
  }
 }