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

后端 未结 9 2133
臣服心动
臣服心动 2020-12-02 15:21

If I have:

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

how do I get the string one back from $ar

相关标签:
9条回答
  • 2020-12-02 15:34

    Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. 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 '';
        }
    
    0 讨论(0)
  • 2020-12-02 15:35

    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!

    0 讨论(0)
  • 2020-12-02 15:40

    If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:

    echo array_keys($array)[$i];
    
    0 讨论(0)
  • 2020-12-02 15:40
    $array = array( 'one' =>'value', 'two' => 'value2' );
    $keys  = array_keys($array);
    echo $keys[0]; // one
    echo $keys[1]; // two
    
    0 讨论(0)
  • 2020-12-02 15:43

    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. 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.

    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 />
    
    0 讨论(0)
  • 2020-12-02 15:44
    $array = array( 'one' =>'value', 'two' => 'value2' );
    
    $allKeys = array_keys($array);
    echo $allKeys[0];
    

    Which will output:

    one
    
    0 讨论(0)
提交回复
热议问题