PHP数组使用教程
无需很多相似的变量,你可以把数据作为元素存储在数组中。
数组中的元素都有自己的 ID,因此可以方便地访问它们。
有三种数组类型:
数值数组
带有数字 ID 键的数组
例子
$names = array("Peter","Quagmire","Joe");
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
以上代码的输出:
Quagmire and Joe are Peter's neighbors
关联数组
数组中的每个 ID 键关联一个值
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
echo "Peter is " . $ages['Peter'] . " years old.";
以上脚本的输出:
Peter is 32 years old.
多维数组
包含一个或多个数组的数组
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
如果输出这个数组的话,应该类似这样:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)