PHP:打印关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6429029/
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
PHP: Printing Associative Array
提问by Tu Hoang
In PHP, I have an associative array like this
在 PHP 中,我有一个像这样的关联数组
$a = array('who' => 'one', 'are' => 'two', 'you' => 'three');
How to write a foreach
loop that goes through the array and access the array key and value so that I can manipulate them (in other words, I would be able to get who
and one
assigned to two variables $key
and $value
?
如何编写一个foreach
遍历数组并访问数组键和值的循环,以便我可以操作它们(换句话说,我将能够获取who
并one
分配给两个变量$key
和$value
?
回答by Thiago Silveira
foreach ($array as $key => $value) {
echo "Key: $key; Value: $value\n";
}
回答by KingCrunch
@Thiago already mentions the way to access the key and the corresponding value. This is of course the correct and preferred solution.
@Thiago 已经提到了访问键和相应值的方法。这当然是正确和首选的解决方案。
However, because you say
然而,因为你说
so I can manipulate them
所以我可以操纵它们
I want to suggest two other approaches
我想建议另外两种方法
If you only want to manipulate the value, access it as reference
foreach ($array as $key => &$value) { $value = 'some new value'; }
If you want to manipulate both the key and the value, you should going an other way
foreach (array_keys($array) as $key) { $value = $array[$key]; unset($array[$key]); // remove old key $array['new key'] = $value; // set value into new key }
如果您只想操作该值,请将其作为参考访问
foreach ($array as $key => &$value) { $value = 'some new value'; }
如果你想同时操作键和值,你应该换一种方式
foreach (array_keys($array) as $key) { $value = $array[$key]; unset($array[$key]); // remove old key $array['new key'] = $value; // set value into new key }