数组能够在单个变量中存储多个值:
键值对:键名 键值
数组中的元素:除了对象,可以存放任意类型的数据
在 PHP 中,array() 函数用于创建数组
数组分类:
数值数组 - 带有数字 ID 键的数组
关联数组 - 带有指定的键的数组,每个键关联一个值
多维数组 - 包含一个或多个数组的数组
数值数组
自动分配 ID 键(ID 键总是从 0 开始)
案例:
$students = array("wcp","zqx","lzs");
echo $students[0];
echo "
";
echo $students[1];
echo "
";
echo $students[2];
echo "
";
print_r($students);
echo "
";
var_dump($students);
?>
案例结果:
人工分配 ID 键
案例
$students[10] = "wcp";
$students[20] = "zqx";
$students[30] = "lzs";
echo $students[10];
echo "
";
echo $students[20];
echo "
";
echo $students[30];
echo "
";
print_r($students);
echo "
";
var_dump($students);
?>
案例结果
获取数组的长度- count() 函数
count() 函数用于返回数组的长度(元素的数量)
案例:
$students = array("wcp","zqx","lzs");
echo count($students);
?>
案例结果:
遍历数值数组
count() 函数用于返回数组的长度(元素的数量)
案例:
$students = array("wcp","zqx","lzs");
for ($i = 0; $i < count($students);$i++){
print_r($i."--".$students[$i]);
echo "
";
}
?>
案例结果:
关联数组
关联数组是使用您分配给数组的指定的键的数组
案例:
$students = array('name' => "wcp",
'age' => "23",
'sex' => true,
'grade' => "79.9");
echo "name:".$students["name"];
echo "
";
echo "age:".$students["age"];
echo "
";
echo "sexe:".$students["sex"];
echo "
";
echo "grade:".$students["grade"];
echo "
";
?>
案例结果:
遍历关联数组
遍历并打印关联数组中的所有值,您可以使用 foreach 循环
案例:
$students = array('name' => "wcp",
'age' => "23",
'sex' => true,
'grade' => "79.9");
foreach($students as $aa){
echo $aa;
echo "
";
}
echo "
";
foreach($students as $key => $value){
echo "key=".$key.",value=".$value;
echo "
";
}
?>
案例结果:
多维数组
一个数组中的值可以是另一个数组,另一个数组的值也可以是一个数组。
依照这种方式,我们可以创建二维或者三维数组:
案例:
$student = array(
1901 => array(
'name' => "AJEST",
'age ' => "24",
'sex' => "男",
'grade' => "79.9"
),
1902 => array(
'name' => "MDM",
'age ' => "23",
'sex' => "女",
'grade' => "59.9"
),
1903 => array(
'name' => "XL",
'age ' => "25",
'sex' => "男",
'grade' => "59.9"
),
);
//print_r($student);
foreach($student as $keya => $valuea){
echo $keya;
echo " ";
foreach($valuea as $keyb => $valuesb){
echo $valuesb;
echo " ";
};
echo "
";
}
echo "
";
foreach($student as $valuea){
foreach($valuea as $valuesb){
echo $valuesb;
echo " ";
};
echo "
";
}
?>
案例结果:
[ 学习链接 ] (https://www.runoob.com/php/php-arrays.html)
愿你
历经山河 仍觉人间值得
历经千帆 归来仍是少年
笑得坦荡 眼里都是太阳
此生尽兴 赤忱善良
以梦为马 不负韶华