php 如何遍历关联数组并获取密钥?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1951690/
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
How to loop through an associative array and get the key?
提问by TheFlash
My associative array:
我的关联数组:
$arr = array(
1 => "Value1",
2 => "Value2",
10 => "Value10"
);
Using the following code, $vis filled with $arr's values
使用以下代码,$v填充了$arr的值
foreach($arr as $v){
echo($v); // Value1, Value2, Value10
}
How do I get $arr's keys instead?
我如何获得$arr's 的钥匙?
foreach(.....){
echo($k); // 1, 2, 10
}
回答by codaddict
回答by Trevor Johns
If you use array_keys(), PHP will give you an array filled with just the keys:
如果你使用array_keys(),PHP 会给你一个只包含键的数组:
$keys = array_keys($arr);
foreach($keys as $key) {
echo($key);
}
Alternatively, you can do this:
或者,您可以这样做:
foreach($arr as $key => $value) {
echo($key);
}
回答by MuhsinFatih
Nobody answered with regular forloop? Sometimes I find it more readable and prefer forover foreach
So here it is:
没有人用常规for循环回答吗?有时候,我觉得它更具可读性和更喜欢for在foreach
所以在这里,它是:
$array = array('key1' => 'value1', 'key2' => 'value2');
$keys = array_keys($array);
for($i=0; $i < count($keys); ++$i) {
echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}
/*
prints:
key1 value1
key2 value2
*/
回答by Htbaa
foreach($array as $k => $v)
Where $k is the key and $v is the value
其中 $k 是键,$v 是值
Or if you just need the keys use array_keys()
或者,如果您只需要密钥,请使用 array_keys()
回答by dmeehan
I use the following loop to get the key and value from an associative array
我使用以下循环从关联数组中获取键和值
foreach ($array as $key => $value)
{
echo "<p>$key = $value</p>";
}
回答by nettux
While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)
虽然可以说不太清楚,但这种方法的速度大约快了大约 3.5 倍(至少在我用来测试的盒子上)
$foo = array(
1 => "Value1",
2 => "Value2",
10 => "Value10"
);
while($bar = each($foo)){
echo $bar[0] . " => " . $bar[1];
}
I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.
我想这是因为 foreach 在迭代之前复制了整个数组。
回答by Jeff Beck
The following will allow you to get at both the key and value at the same time.
以下将允许您同时获取键和值。
foreach ($arr as $key => $value)
{
echo($key);
}
回答by TheFlash
Oh I found it in the PHP manual.
哦,我在PHP 手册中找到了它。
foreach ($array as $key => $value){
statement
}
The current element's key will be assigned to the variable $keyon each loop.
当前元素的键将在每个循环中分配给变量$key。
回答by ?aphink
Use $key => $valto get the keys:
使用$key => $val领取钥匙:
<?php
$arr = array(
1 => "Value1",
2 => "Value2",
10 => "Value10",
);
foreach ($arr as $key => $val) {
print "$key\n";
}
?>
回答by maurice
<?php
$names = array("firstname"=>"maurice",
"lastname"=>"muteti",
"contact"=>"7844433339");
foreach ($names as $name => $value) {
echo $name." ".$value."</br>";
}
print_r($names);
?>

