PHP 多维数组

Building, traversing and column-sorting 2D and 3D arrays.

Beginner
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.7

Matrix 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
        )

)
6

count($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
80
PHP 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
    b1

Recursion is the natural fit for trees, but mind the depth limit. Menus and categories are shallow; XML or JSON parsing may not be.

Friends & Partners