PHP 多维数组
Building, traversing and column-sorting 2D and 3D arrays.
Key PointsA multidimensional array is just an array of arrays — no dimension limit.
Two-dimensional arrays
PHP
<?php
$students = [
["name" => "Tom", "scores" => [90, 85, 88]],
["name" => "Amy", "scores" => [95, 92, 91]],
];
echo $students[0]["name"], "\n";
echo $students[1]["scores"][0], "\n";
echo count($students), "\n";
echo count($students[0]["scores"]), "\n";
foreach ($students as $s) {
$avg = array_sum($s["scores"]) / count($s["scores"]);
printf("%s 平均 %.1f\n", $s["name"], $avg);
}Output
Tom
95
2
3
Tom 平均 87.7
Amy 平均 92.7Matrix operations
PHP
<?php
$m = [
[1, 2],
[3, 4],
];
echo $m[1][0], "\n";
// 转置
$t = [];
foreach ($m as $i => $row) {
foreach ($row as $j => $v) {
$t[$j][$i] = $v;
}
}
print_r($t);
// 递归计数
echo count($m, COUNT_RECURSIVE), "\n";Output
3
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 2
[1] => 4
)
)
6count($m, COUNT_RECURSIVE) is 6 — two outer elements plus four inner. The default counts only the top level.
Column extraction and sorting
PHP
<?php
$rows = [
["id" => 3, "name" => "Bob", "age" => 35],
["id" => 1, "name" => "Tom", "age" => 30],
["id" => 2, "name" => "Amy", "age" => 25],
];
print_r(array_column($rows, "name"));
// 以 id 为键重建
$byId = array_column($rows, null, "id");
echo $byId[2]["name"], "\n";
// 按年龄升序
usort($rows, fn($a, $b) => $a["age"] <=> $b["age"]);
print_r(array_column($rows, "name"));Output
Array
(
[0] => Bob
[1] => Tom
[2] => Amy
)
Amy
Array
(
[0] => Amy
[1] => Tom
[2] => Bob
)array_column($rows, null, "id") is underused: pass null to keep whole rows, the third argument as the key. Great for lookup maps.
Three dimensions and ragged arrays
PHP
<?php
$data = [
"2023" => [
"Q1" => ["sales" => 100, "cost" => 60],
"Q2" => ["sales" => 140, "cost" => 80],
],
"2024" => [
"Q1" => ["sales" => 160, "cost" => 90],
],
];
foreach ($data as $year => $quarters) {
$sum = 0;
foreach ($quarters as $q => $row) {
$sum += $row["sales"];
}
echo "$year 总销售 $sum\n";
}
echo $data["2023"]["Q2"]["cost"], "\n";Output
2023 总销售 240
2024 总销售 160
80PHP arrays are naturally ragged: 2024 has only Q1. That flexibility invites missing-key bugs — use
?? while traversing.Walking nested structures
PHP
<?php
$tree = [
"name" => "root",
"children" => [
["name" => "a", "children" => []],
["name" => "b", "children" => [
["name" => "b1", "children" => []],
]],
],
];
function walk(array $node, int $depth = 0): void {
echo str_repeat(" ", $depth) . $node["name"] . "\n";
foreach ($node["children"] as $child) {
walk($child, $depth + 1);
}
}
walk($tree);Output
root
a
b
b1Recursion is the natural fit for trees, but mind the depth limit. Menus and categories are shallow; XML or JSON parsing may not be.
二维数组
PHP
<?php
$students = [
["name" => "Tom", "scores" => [90, 85, 88]],
["name" => "Amy", "scores" => [95, 92, 91]],
];
echo $students[0]["name"], "\n";
echo $students[1]["scores"][0], "\n";
echo count($students), "\n";
echo count($students[0]["scores"]), "\n";
foreach ($students as $s) {
$avg = array_sum($s["scores"]) / count($s["scores"]);
printf("%s 平均 %.1f\n", $s["name"], $avg);
}Output
Tom
95
2
3
Tom 平均 87.7
Amy 平均 92.7矩阵运算
PHP
<?php
$m = [
[1, 2],
[3, 4],
];
echo $m[1][0], "\n";
// 转置
$t = [];
foreach ($m as $i => $row) {
foreach ($row as $j => $v) {
$t[$j][$i] = $v;
}
}
print_r($t);
// 递归计数
echo count($m, COUNT_RECURSIVE), "\n";Output
3
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 2
[1] => 4
)
)
6count($m, COUNT_RECURSIVE) 是 6:外层 2 个元素 + 内层 4 个元素。默认的 count($m) 只数第一层,得 2。
按列取值与排序
PHP
<?php
$rows = [
["id" => 3, "name" => "Bob", "age" => 35],
["id" => 1, "name" => "Tom", "age" => 30],
["id" => 2, "name" => "Amy", "age" => 25],
];
print_r(array_column($rows, "name"));
// 以 id 为键重建
$byId = array_column($rows, null, "id");
echo $byId[2]["name"], "\n";
// 按年龄升序
usort($rows, fn($a, $b) => $a["age"] <=> $b["age"]);
print_r(array_column($rows, "name"));Output
Array
(
[0] => Bob
[1] => Tom
[2] => Amy
)
Amy
Array
(
[0] => Amy
[1] => Tom
[2] => Bob
)array_column($rows, null, "id") 是常被忽略的用法:第二个参数传 null,整个子数组作值,第三个参数指定的列作键。查表、去重、关联都用它。
三维与不规则数组
PHP
<?php
$data = [
"2023" => [
"Q1" => ["sales" => 100, "cost" => 60],
"Q2" => ["sales" => 140, "cost" => 80],
],
"2024" => [
"Q1" => ["sales" => 160, "cost" => 90],
],
];
foreach ($data as $year => $quarters) {
$sum = 0;
foreach ($quarters as $q => $row) {
$sum += $row["sales"];
}
echo "$year 总销售 $sum\n";
}
echo $data["2023"]["Q2"]["cost"], "\n";Output
2023 总销售 240
2024 总销售 160
80PHP 的数组天然不规则:
$data["2024"] 只有 Q1,另一个有 Q2。这比固定形状的结构灵活,也更容易出现「某个键不存在」的 bug——遍历时用 ?? 兜底。遍历嵌套结构
PHP
<?php
$tree = [
"name" => "root",
"children" => [
["name" => "a", "children" => []],
["name" => "b", "children" => [
["name" => "b1", "children" => []],
]],
],
];
function walk(array $node, int $depth = 0): void {
echo str_repeat(" ", $depth) . $node["name"] . "\n";
foreach ($node["children"] as $child) {
walk($child, $depth + 1);
}
}
walk($tree);Output
root
a
b
b1递归函数处理树形结构最直接。但要注意递归深度——层级太深会撞 PHP 的栈限制,菜单、分类这类数据通常只有几层,问题不大;解析 XML 或 JSON 时就要小心了。