当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > PHP 数组
An array can store one or more values in a single variable name.
数组(array)的作用是:为一个同名变量存储一个或多个值。
When working with PHP, sooner or later, you might want to create many similar variables.
当你书写PHP时,你都会或多或少地创建几个关系相类似的变量。
Instead of having many similar variables, you can store the data as elements in an array.
为了避免使用多个类似变量(这样对你的记忆和程序编写来说会很麻烦),你可以把所有的数据分别作为一个元素存储在一个数组里。
Each element in the array has its own ID so that it can be easily accessed.
数组中每个元素都有自己独立的ID,这样便于访问。
There are three different kind of arrays:
下面列举了不同种类的数组:
A numeric array stores each element with a numeric ID key.
数字数组中的每个元素包含一个数字ID。
There are different ways to create a numeric array.
下面列举几种不同的方法来创建一个数字数组:
In this example the ID key is automatically assigned:
这个例子,元素的ID是自动生成的:
$names = array("Peter","Quagmire","Joe"); |
In this example we assign the ID key manually:
这个例子中元素的ID是我们手动生成的:
$names[0] = "Peter"; |
The ID keys can be used in a script:
这里的ID关键词可以应用于一个脚本程序当中:
<?php $names[0] = "Peter"; echo $names[1] . " and " . $names[2] . |
The code above will output:
上述代码执行后将输出下面的结果:
Quagmire and Joe are Peter's neighbors |
An associative array, each ID key is associated with a value.
这个数组中的每个ID都是与一个值联系在一块(即它们是配套的,组合在一块的)。
When storing data about specific named values, a numerical array is not always the best way to do it.
如果某个值已被命名,那么我就再使用数字数组来存储它的值就不方便了。
With associative arrays we can use the values as keys and assign values to them.
通过使用联合数组,我们可以把关键词作为对象,并给它们赋值。
In this example we use an array to assign ages to the different persons:
在这个例子当中,我们通过使用一个数组给不同的人指定了不同的年龄:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); |
This example is the same as example 1, but shows a different way of creating the array:
这个例子和案例1类似,它使用了另外一种创建数组的方法:
$ages['Peter'] = "32"; |
The ID keys can be used in a script:
这里的ID关键词可以在脚本程序中使用:
<?php $ages['Peter'] = "32"; echo "Peter is " . $ages['Peter'] . " years old."; |
The code above will output:
上述代码执行后将输出下面的结果:
Peter is 32 years old. |
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
对于一个多位数组来说没,其中的每个元素都可以视为一个数组;这些二级数组中的每个元素又可以视为一个数组,以此类推。
In this example we create a multidimensional array, with automatically assigned ID keys:
在这个案例当中,我们建立了一个多位数组,它的ID是自动生成的:
$families = array |
The array above would look like this if written to the output:
上述数组的执行结果如下:
Array |