[英]PHP: Printing Associative Array
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
数组的foreach
循环并访问数组的键和值,以便我可以操纵它们(换句话说,我将能够将who
和one
分配给两个变量$key
和$value
?
foreach ($array as $key => $value) {
echo "Key: $key; Value: $value\n";
}
@Thiago already mentions the way to access the key and the corresponding value. @Thiago已经提到了访问密钥和相应值的方法。 This is of course the correct and preferred solution. 当然,这是正确且首选的解决方案。
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.