多维数组 #

一、多维数组概述 #

多维数组是指数组中的元素也是数组,形成嵌套结构。

1.1 常见维度 #

  • 二维数组:数组中的元素是一维数组
  • 三维数组:数组中的元素是二维数组
  • 多维数组:三层及以上嵌套

二、二维数组 #

2.1 创建二维数组 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25, 'city' => 'Beijing'],
    ['name' => 'Jane', 'age' => 30, 'city' => 'Shanghai'],
    ['name' => 'Bob', 'age' => 35, 'city' => 'Guangzhou']
];

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

2.2 访问元素 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30]
];

echo $users[0]['name'];
echo $users[1]['age'];

$matrix = [
    [1, 2, 3],
    [4, 5, 6]
];

echo $matrix[0][0];
echo $matrix[1][2];

2.3 修改元素 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30]
];

$users[0]['age'] = 26;
$users[1]['city'] = 'Shanghai';

print_r($users);

2.4 添加元素 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25]
];

$users[] = ['name' => 'Jane', 'age' => 30];
$users[0]['city'] = 'Beijing';

print_r($users);

三、遍历二维数组 #

3.1 嵌套foreach #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30]
];

foreach ($users as $user) {
    foreach ($user as $key => $value) {
        echo "$key: $value\n";
    }
    echo "---\n";
}

3.2 遍历并格式化 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30]
];

foreach ($users as $user) {
    echo "{$user['name']} is {$user['age']} years old\n";
}

3.3 带索引遍历 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30]
];

foreach ($users as $index => $user) {
    echo "User #" . ($index + 1) . ": {$user['name']}\n";
}

3.4 遍历矩阵 #

php
<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . ' ';
    }
    echo "\n";
}

四、三维数组 #

4.1 创建三维数组 #

php
<?php
$company = [
    'engineering' => [
        'developers' => [
            ['name' => 'John', 'role' => 'Senior'],
            ['name' => 'Jane', 'role' => 'Junior']
        ],
        'testers' => [
            ['name' => 'Bob', 'role' => 'QA']
        ]
    ],
    'marketing' => [
        'managers' => [
            ['name' => 'Alice', 'role' => 'Lead']
        ]
    ]
];

4.2 访问三维数组 #

php
<?php
echo $company['engineering']['developers'][0]['name'];
echo $company['marketing']['managers'][0]['role'];

4.3 遍历三维数组 #

php
<?php
foreach ($company as $department => $teams) {
    echo "Department: $department\n";
    foreach ($teams as $team => $members) {
        echo "  Team: $team\n";
        foreach ($members as $member) {
            echo "    - {$member['name']} ({$member['role']})\n";
        }
    }
}

五、多维数组操作 #

5.1 提取列 #

php
<?php
$users = [
    ['id' => 1, 'name' => 'John', 'age' => 25],
    ['id' => 2, 'name' => 'Jane', 'age' => 30],
    ['id' => 3, 'name' => 'Bob', 'age' => 35]
];

$names = array_column($users, 'name');
print_r($names);

$idNameMap = array_column($users, 'name', 'id');
print_r($idNameMap);

5.2 过滤 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25, 'active' => true],
    ['name' => 'Jane', 'age' => 30, 'active' => false],
    ['name' => 'Bob', 'age' => 35, 'active' => true]
];

$active = array_filter($users, fn($u) => $u['active']);
print_r($active);

$over25 = array_filter($users, fn($u) => $u['age'] > 25);
print_r($over25);

5.3 排序 #

php
<?php
$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 20]
];

usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
print_r($users);

usort($users, fn($a, $b) => strcmp($a['name'], $b['name']));
print_r($users);

5.4 映射 #

php
<?php
$products = [
    ['name' => 'Apple', 'price' => 100],
    ['name' => 'Banana', 'price' => 50]
];

$withTax = array_map(function($p) {
    $p['priceWithTax'] = $p['price'] * 1.1;
    return $p;
}, $products);

print_r($withTax);

5.5 归约 #

php
<?php
$orders = [
    ['product' => 'Apple', 'quantity' => 2, 'price' => 100],
    ['product' => 'Banana', 'quantity' => 3, 'price' => 50],
    ['product' => 'Cherry', 'quantity' => 1, 'price' => 200]
];

$total = array_reduce($orders, fn($carry, $order) => 
    $carry + ($order['quantity'] * $order['price'])
, 0);

echo $total;

六、矩阵操作 #

6.1 创建矩阵 #

php
<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

6.2 矩阵转置 #

php
<?php
function transpose(array $matrix): array
{
    return array_map(null, ...$matrix);
}

$matrix = [
    [1, 2, 3],
    [4, 5, 6]
];

$transposed = transpose($matrix);
print_r($transposed);

6.3 矩阵加法 #

php
<?php
function matrixAdd(array $a, array $b): array
{
    $result = [];
    for ($i = 0; $i < count($a); $i++) {
        for ($j = 0; $j < count($a[$i]); $j++) {
            $result[$i][$j] = $a[$i][$j] + $b[$i][$j];
        }
    }
    return $result;
}

6.4 矩阵乘法 #

php
<?php
function matrixMultiply(array $a, array $b): array
{
    $rowsA = count($a);
    $colsA = count($a[0]);
    $colsB = count($b[0]);
    
    $result = array_fill(0, $rowsA, array_fill(0, $colsB, 0));
    
    for ($i = 0; $i < $rowsA; $i++) {
        for ($j = 0; $j < $colsB; $j++) {
            for ($k = 0; $k < $colsA; $k++) {
                $result[$i][$j] += $a[$i][$k] * $b[$k][$j];
            }
        }
    }
    
    return $result;
}

七、实际应用 #

7.1 购物车 #

php
<?php
class Cart
{
    private array $items = [];
    
    public function add(array $product, int $quantity = 1): void
    {
        $id = $product['id'];
        
        if (isset($this->items[$id])) {
            $this->items[$id]['quantity'] += $quantity;
        } else {
            $this->items[$id] = [
                'product' => $product,
                'quantity' => $quantity
            ];
        }
    }
    
    public function getTotal(): float
    {
        return array_reduce($this->items, fn($carry, $item) => 
            $carry + ($item['product']['price'] * $item['quantity'])
        , 0.0);
    }
    
    public function getItems(): array
    {
        return $this->items;
    }
}

7.2 树形结构 #

php
<?php
function buildTree(array $items, int $parentId = 0): array
{
    $tree = [];
    
    foreach ($items as $item) {
        if ($item['parent_id'] === $parentId) {
            $children = buildTree($items, $item['id']);
            if ($children) {
                $item['children'] = $children;
            }
            $tree[] = $item;
        }
    }
    
    return $tree;
}

$categories = [
    ['id' => 1, 'name' => 'Electronics', 'parent_id' => 0],
    ['id' => 2, 'name' => 'Phones', 'parent_id' => 1],
    ['id' => 3, 'name' => 'Laptops', 'parent_id' => 1],
    ['id' => 4, 'name' => 'iPhone', 'parent_id' => 2],
];

$tree = buildTree($categories);
print_r($tree);

7.3 分组统计 #

php
<?php
function groupAndSum(array $items, string $groupKey, string $sumKey): array
{
    $result = [];
    
    foreach ($items as $item) {
        $group = $item[$groupKey];
        
        if (!isset($result[$group])) {
            $result[$group] = 0;
        }
        
        $result[$group] += $item[$sumKey];
    }
    
    return $result;
}

$sales = [
    ['product' => 'Apple', 'region' => 'North', 'amount' => 100],
    ['product' => 'Banana', 'region' => 'North', 'amount' => 50],
    ['product' => 'Apple', 'region' => 'South', 'amount' => 80],
];

$byRegion = groupAndSum($sales, 'region', 'amount');
print_r($byRegion);

八、最佳实践 #

8.1 使用有意义的键名 #

php
<?php
$user = [
    'personal' => [
        'name' => 'John',
        'age' => 25
    ],
    'contact' => [
        'email' => 'john@example.com',
        'phone' => '123-456-7890'
    ]
];

8.2 避免过深嵌套 #

php
<?php
$deep = [
    'level1' => [
        'level2' => [
            'level3' => [
                'level4' => 'value'
            ]
        ]
    ]
];

class Config
{
    public function get(string $key, mixed $default = null): mixed
    {
        $keys = explode('.', $key);
        $value = $this->data;
        
        foreach ($keys as $k) {
            if (!isset($value[$k])) {
                return $default;
            }
            $value = $value[$k];
        }
        
        return $value;
    }
}

8.3 使用对象代替复杂数组 #

php
<?php
class User
{
    public function __construct(
        public string $name,
        public int $age,
        public Address $address
    ) {}
}

class Address
{
    public function __construct(
        public string $city,
        public string $country
    ) {}
}

九、总结 #

本章学习了:

  • 二维数组的创建和访问
  • 三维数组的结构
  • 多维数组的遍历
  • 多维数组的操作
  • 矩阵操作
  • 实际应用场景
  • 最佳实践

下一章将学习PHP字符串。

最后更新:2026-03-26