简体   繁体   English

php:如何从数字索引中获取关联数组键?

[英]php: how to get associative array key from numeric index?

If I have:如果我有:

$array = array( 'one' =>'value', 'two' => 'value2' );

how do I get the string one back from $array[1] ?我如何从$array[1]取回字符串one

You don't.你没有。 Your array doesn't have a key [1] .您的数组没有键[1] You could:你可以:

  • Make a new array, which contains the keys:创建一个包含键的新数组:

     $newArray = array_keys($array); echo $newArray[0];

    But the value "one" is at $newArray[0] , not [1] .但是值 "one" 是$newArray[0] ,而不是[1]
    A shortcut would be:一个快捷方式是:

     echo current(array_keys($array));
  • Get the first key of the array:获取数组的第一个键:

     reset($array); echo key($array);
  • Get the key corresponding to the value "value":获取值“value”对应的key:

     echo array_search('value', $array);

This all depends on what it is exactly you want to do.这一切都取决于您究竟想要做什么。 The fact is, [1] doesn't correspond to "one" any which way you turn it.事实是, [1]不对应于任何你转动它的“一”。

$array = array( 'one' =>'value', 'two' => 'value2' );

$allKeys = array_keys($array);
echo $allKeys[0];

Which will output:这将输出:

one

如果您只打算特别使用一个键,则可以用一行完成此操作,而不必为所有键存储一个数组:

echo array_keys($array)[$i];

Or if you need it in a loop或者,如果您需要循环使用它

foreach ($array as $key => $value)
{
    echo $key . ':' . $value . "\n";
}
//Result: 
//one:value
//two:value2
$array = array( 'one' =>'value', 'two' => 'value2' );
$keys  = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two

The key function helped me and is very simple:关键功能对我有帮助,而且非常简单:

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. key() 函数只返回内部指针当前指向的数组元素的键。 It does not move the pointer in any way.它不会以任何方式移动指针。 If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.如果内部指针指向元素列表的末尾或数组为空,则 key() 返回 NULL。

Example:示例:

<?php
    $array = array(
        'fruit1' => 'apple',
        'fruit2' => 'orange',
        'fruit3' => 'grape',
        'fruit4' => 'apple',
        'fruit5' => 'apple');

    // this cycle echoes all associative array
    // key where value equals "apple"
    while ($fruit_name = current($array)) {
        if ($fruit_name == 'apple') {
            echo key($array).'<br />';
        }
        next($array);
    }
?>

The above example will output:上面的例子将输出:

fruit1<br />
fruit4<br />
fruit5<br />

You might do it this way:你可以这样做:

function asoccArrayValueWithNumKey(&$arr, $key) {
   if (!(count($arr) > $key)) return false;
   reset($array);
   $aux   = -1;
   $found = false;
   while (($auxKey = key($array)) && !$found) {
      $aux++;
      $found = ($aux == $key);
   }
   if ($found) return $array[$auxKey];
   else return false;
}

$val = asoccArrayValueWithNumKey($array, 0);
$val = asoccArrayValueWithNumKey($array, 1);
etc...

Haven't tryed the code, but i'm pretty sure it will work.还没有尝试过代码,但我很确定它会起作用。

Good luck!祝你好运!

If it is the first element, ie $array[0] , you can try:如果它是第一个元素,即$array[0] ,您可以尝试:

echo key($array);

If it is the second element, ie $array[1] , you can try:如果它是第二个元素,即$array[1] ,您可以尝试:

next($array);
echo key($array);

I think this method is should be used when required element is the first, second or at most third element of the array.我认为当所需元素是数组的第一个、第二个或最多第三个元素时,应该使用这种方法。 For other cases, loops should be used otherwise code readability decreases.对于其他情况,应使用循环,否则代码可读性会降低。

One more example:再举一个例子:

Get the most frequent occurrence(s) in an array:获取数组中最常出现的次数:

PHP >= 7.3: PHP >= 7.3:

$ php --version
PHP 7.4.3 (cli) (built: Oct  6 2020 15:47:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

$ php -a
Interactive mode enabled

php > $a = array_count_values(array('abc','abc','def','def','def'));
php > var_dump($a);
array(2) {
  ["abc"]=>
  int(2)
  ["def"]=>
  int(3)
}
php > arsort($a);
php > var_dump($a);
array(2) {
  ["def"]=>
  int(3)
  ["abc"]=>
  int(2)
}
php > var_dump(array_key_first($a));
string(3) "def"
php > var_dump(array_keys($a)[1]);
string(3) "abc"

If you have the key, you can easily query the value (= the frequency).如果您有密钥,则可以轻松查询值(= 频率)。

just posting another solution for those that array_keys() is not working只是为那些 array_keys() 不起作用的人发布另一个解决方案

$myAssociativeArray = [
  'name' => 'sun',
  'age' => 21
);

$arrayKeys = [];
foreach($myAssociativeArray as $key => $val){
    array_push($arrayKeys, $key);
}

print_r($arrayKeys)

// ['name', 'age']

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array.扩展 Ram Dane 的答案, key函数是获取数组当前索引键的另一种方法。 You can create the following function,您可以创建以下功能,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM