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

后端 未结 9 2188
臣服心动
臣服心动 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: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!

提交回复
热议问题