PHP:从数组中获取密钥?

2022-08-30 09:03:34

我确信这是PHP中超级简单和内置的功能,但我还没有看到它。

以下是我目前正在做的事情:

foreach($array as $key => $value) {
    echo $key; // Would output "subkey" in the example array
    print_r($value);
}

我是否可以做如下操作,从而避免在每个foreach循环中编写“$key = > $value”?(伪代码)

foreach($array as $subarray) {
    echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
    print_r($value);
}

谢谢!

数组:

Array
(
    [subKey] => Array
        (
            [value] => myvalue
        )

)

答案 1

您可以使用 key()

<?php
$array = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4
);

while($element = current($array)) {
    echo key($array)."\n";
    next($array);
}
?>

答案 2

使用array_search函数。

php.net 示例

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;