PHP 中的数组非常灵活,元素本身也可以是数组,这样就构成了多维数组。实际开发中最常见的是二维数组,比如保存一张学生成绩表。
二维数组的定义
索引数组写法
<?php
$students = [
['张三', 18, 90],
['李四', 20, 85],
['王五', 19, 78],
];
echo $students[0][0]; // 输出:张三
外层数组的每个元素又是一个数组,访问时用两层下标:第一层是第几个学生,第二层是姓名、年龄、成绩。
关联数组写法
关联数组用字符串作键,语义更清晰:
<?php
$students = [
[
'name' => '张三',
'age' => 18,
'score' => 90,
],
[
'name' => '李四',
'age' => 20,
'score' => 85,
],
];
echo $students[1]['name']; // 输出:李四
二维数组的遍历
嵌套 foreach(推荐)
<?php
$students = [
['name' => '张三', 'score' => 90],
['name' => '李四', 'score' => 85],
];
foreach ($students as $student) {
echo "姓名:{$student['name']},成绩:{$student['score']}\n";
}
也可以同时取出外层的键:
<?php
foreach ($students as $index => $student) {
echo "第 " . ($index + 1) . " 位:{$student['name']}\n";
}
嵌套 for 循环(纯索引数组)
<?php
$scores = [
[90, 85, 77],
[66, 92, 88],
];
for ($i = 0; $i < count($scores); $i++) {
for ($j = 0; $j < count($scores[$i]); $j++) {
echo $scores[$i][$j] . ' ';
}
echo "\n";
}
for 只适合连续的索引数组,关联数组请使用 foreach。
三维数组
多维数组可以继续嵌套,例如按班级再分一层:
<?php
$school = [
'一班' => [
['name' => '张三', 'score' => 90],
['name' => '李四', 'score' => 85],
],
'二班' => [
['name' => '王五', 'score' => 78],
],
];
foreach ($school as $class => $students) {
echo "班级:$class\n";
foreach ($students as $student) {
echo " {$student['name']}:{$student['score']}\n";
}
}
常用操作
动态添加元素
<?php
$students = [];
$students[] = ['name' => '张三', 'score' => 90];
$students[] = ['name' => '李四', 'score' => 85];
取出某一列
PHP 5.5+ 提供了 array_column,可以很方便地抽出一列:
<?php
$names = array_column($students, 'name');
// ['张三', '李四']
统计元素个数
<?php
echo count($students); // 外层元素个数
echo count($students, 1); // 递归统计所有元素
小结
- 数组的元素仍是数组,就是多维数组,访问时用多层下标或键名
- 遍历多维数组用嵌套的
foreach,纯索引数组也可以用嵌套for array_column能快速抽取某一列,处理二维数组非常实用