php 在不知道一对关联数组中的键的情况下获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11145185/
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-24 23:50:24  来源:igfitidea点击:

Get value without knowing key in one-pair-associative-array

phparraysassociative-array

提问by Qiao

There is an associative array with only onepair key=>value.

有一个只有一对的关联数组key=>value

I don't know it's key, but I need to get it's value:

我不知道这是关键,但我需要得到它的价值:

$array = array('???' => 'value');
$value = // ??

$array[0]doesn't work.

$array[0]不起作用。

How can I get it's value?

我怎样才能得到它的价值?

回答by nickb

You can also do either of the following functions to get the value since there's only one element in the array.

您还可以执行以下任一函数来获取值,因为数组中只有一个元素。

$value = reset( $array);
$value = current( $array);
$value = end( $array);

Also, if you want to use array_keys(), you'd need to do:

另外,如果您想使用array_keys(),则需要执行以下操作:

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

To get the value.

去获取价值。

As some more options, you can ALSO use array_pop()or array_shift()to get the value:

作为更多选项,您还可以使用array_pop()array_shift()获取值:

$value = array_pop( $array);
$value = array_shift( $array);

Finally, you can use array_values()to get all the values of the array, then take the first:

最后,您可以使用array_values()获取数组的所有值,然后取第一个:

$values = array_values( $array);
echo $values[0];


Of course, there are lots of other alternatives; some silly, some useful.

当然,还有很多其他选择;有些傻,有些有用。

$value = pos($array);
$value = implode('', $array);
$value = current(array_slice($array, 0, 1));
$value = current(array_splice($array, 0, 1));
$value = vsprintf('%s', $array);
foreach($array as $value);
list(,$value) = each($array);

回答by John Conde

array_keys()will get the key for you

array_keys()会为你拿到钥匙

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

回答by Mathieu Dumoulin

What you want is to retrieve the first item?

你想要的是检索第一项?

$value = reset($array);
$key = key($array);

回答by Farahmand

You should use array_values

你应该使用 array_values

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