Php 简明教程

PHP - Associative Array

如果 PHP 数组中的每个元素都是键值对,则这样的数组称为 associative array 。在这类型数组中,每个值都由其关联的键而不是索引标识。

If each element in a PHP array is a key-value pair, such an array is called an associative array. In this type of array, each value is identified by its associated key and not an index.

  1. Associative arrays are used to implement data structures such as dictionary, maps, trees, etc.

  2. In PHP, the "⇒" symbol is used to establish association between a key and its value.

How to Declare an Associative Array in PHP?

可以使用两种声明数组的方法——array() 函数和方括号表示法。

Both the approaches of declaring an array – the array() function and the square bracket notation – can be used.

$arr1 = array(
   "Maharashtra"=>"Mumbai",
   "Telangana"=>"Hyderabad",
   "UP"=>"Lucknow",
   "Tamilnadu"=>"Chennai"
);

$arr2 = ["Maharashtra"=>"Mumbai",
   "Telangana"=>"Hyderabad",
   "UP"=>"Lucknow",
   "Tamilnadu"=>"Chennai"];

如果我们调用 var_dump() 函数,则以上两个数组将显示相似的结构 −

If we call the var_dump() function, both the above arrays will show the similar structure −

array(4) {
   ["Maharashtra"]=>
   string(6) "Mumbai"
   ["Telangana"]=>
   string(9) "Hyderabad
   ["UP"]=>
   string(7) "Lucknow"
   ["Tamilnadu"]=>
   string(7) "Chennai"
}

关联数组中每个元素的 key 部分可以是任意数字(整数、浮点数或布尔值)或字符串。 value 部分可以是任意类型。但是,浮点数键会被强制转换为整数。因此,布尔值 true/false 用作“1”或“0”作为键。

The key part of each element in an associative array can be any number (integer, float or Boolean), or a string. The value part can be of any type. However, the float key is cast to an integer. So, a Boolean true/false is used as "1" or "0" as the key.

Example

请看以下示例:

Take a look at the following example −

<?php
   $arr1 = array(
      10=>"hello",
      5.75=>"world",
      -5=>"foo",
      false=>"bar"
   );
   var_dump($arr1);
?>

它将生成以下 output

It will produce the following output

array(4) {
  [10]=>
  string(5) "hello"
  [5]=>
  string(5) "world"
  [-5]=>
  string(3) "foo"
  [0]=>
  string(3) "bar"
}

请注意,键 5.75 会四舍五入到 5,并且键“true”反映为“0”。如果同一个键在数组中出现多次,则最后出现的键值对将保留,从而舍弃键与较早值的关联。

Note that the key 5.75 gets rounded to 5, and the key "true" is reflected as "0". If the same key appears more than once in an array, the key-value pair that appears last will be retained, discarding the association of the key with earlier value.

PHP 在内部甚至将索引数组视为关联数组,其中索引实际上是值的键。这意味着 0 索引处的值具有等于“0”的键,依此类推。对索引数组执行 var_dump() 也会显示出 PHP 数组的这一特性。

PHP internally treats even an indexed array as an associative array, where the index is actually the key of the value. It means the value at the 0th index has a key equal to "0", and so on. A var_dump() on an indexed array also brings out this characteristics of a PHP array.

Iterating a PHP Associative Array

foreach 循环是遍历关联数组最简单的方法,并且是最好的方法,尽管也可以使用其他类型的循环方法。

A foreach loop is the easiest and ideal for iterating through an associative array, although any other type of loop can also be used with some maneuver.

Example

让我们看看 foreach 的循环实现,每个键值对都在两个变量中解包。

Let us look at the foreach loop implementation, with each key value pair unpacked in two variables.

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai",
      "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow",
      "Tamilnadu"=>"Chennai"
   );

   foreach ($capitals as $k=>$v) {
      echo "Capital of $k is $v \n";
   }
?>

它将生成以下 output

It will produce the following output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

还有另一种在 PHP 中使用 foreach 循环的方法,其中每个元素都存储在一个变量中。然后,我们可以使用 array_search() 分离键和值部分,并使用它们在循环中。

There is another way of using the foreach loop in PHP, where each element is stored in a variable. We can then separate the key and value parts using array_search() and use them in the loop body.

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai",
      "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow",
      "Tamilnadu"=>"Chennai"
   );

   foreach ($capitals as $pair) {
      $cap = array_search($pair, $capitals);
      echo "Capital of $cap is $capitals[$cap] \n";
   }
?>

它将生成以下 output

It will produce the following output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

若要使用 for、 whiledo-while 循环,我们首先必须获取所有键的数组(使用 array_keys()),查找大小并将其用作循环语法中的测试条件。

To use for, while or do-while loop, we have to first get the array of all the keys (use array_keys()), find the size and use it as the test condition in the loop syntax.

Example

以下是如何使用 for 循环来遍历关联数组 −

Here is how we can use a for loop to traverse an associative array −

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai",
      "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow",
      "Tamilnadu"=>"Chennai"
   );
   $keys=array_keys($capitals);

   for ($i=0; $i<count($keys); $i++){
      $cap = $keys[$i];
      echo "Capital of $cap is $capitals[$cap] \n";
   }
?>

它将生成以下 output

It will produce the following output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

Accessing the Value with its Key

在关联数组中,键是值而不是索引的标识符。因此,要获取与特定键关联的值,请使用 $arr[key] 语法。同样的语法也可以用于更新特定键的值。

In an associative array, the key is the identifier of value instead of index. Hence, to fetch value associated with a certain key, use $arr[key] syntax. The same can be used to update the value of a certain key.

Example

在以下代码中,声明了一个关联数组 $arr1 。创建了另一个数组 $arr2 ,使其储存 $arr1 中的每对元素,并且每个键的值都加倍。

In the following code, an associative array $arr1 is declared. Another array $arr2 is created such that it stores each pair from $arr1 with the value of each key being doubled.

<?php
   $arr1 = array("a"=>10, "b"=>20, "c"=>30, "d"=>40);
   foreach ($arr1 as $k=>$v){
      $arr2[$k] = $v*2;
   }
   print_r($arr2);
?>

它将生成以下 output

It will produce the following output

Array
(
   [a] => 20
   [b] => 40
   [c] => 60
   [d] => 80
)

此处使用的 print_r() 函数以易于理解的人类可读形式显示存储在数组中的数据。

The print_r() function used here displays the data stored in the array in an easy to understand human readable form.