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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:21:42  来源:igfitidea点击:

PHP: Printing Associative Array

phpassociative-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 foreachloop 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 whoand oneassigned to two variables $keyand $value?

如何编写一个foreach遍历数组并访问数组键和值的循环,以便我可以操作它们(换句话说,我将能够获取whoone分配给两个变量$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

我想建议另外两种方法

  1. If you only want to manipulate the value, access it as reference

    foreach ($array as $key => &$value) {
      $value = 'some new value';
    }
    
  2. 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
    }
    
  1. 如果您只想操作该值,请将其作为参考访问

    foreach ($array as $key => &$value) {
      $value = 'some new value';
    }
    
  2. 如果你想同时操作键和值,你应该换一种方式

    foreach (array_keys($array) as $key) {
      $value = $array[$key];
      unset($array[$key]); // remove old key
      $array['new key'] = $value; // set value into new key
    }