跳至内容

数组

这篇讲 PHP 数组的三种类型——索引数组、关联数组和多维数组——以及创建、遍历、修改和排序的方法。数组是 PHP 最强大也最常用的数据结构。

数组概述

数组可以在单个变量中存储多个值。PHP 支持三种数组类型:

  • 索引数组:带数字索引的数组
  • 关联数组:带指定键名的数组
  • 多维数组:包含一个或多个数组的数组

数组的创建

PHP 中 array() 和短数组语法 [] 等价,推荐使用后者:

<?php
// 传统写法
$arr = array("foo" => "bar", "bar" => "foo");

// 短数组语法(推荐)
$arr = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

数组可以任意嵌套:

<?php
$data = [
    "foo" => "bar",
    42    => 24,
    "multi" => [
        "nested" => [
            "key" => "value"
        ]
    ]
];

echo $data["multi"]["nested"]["key"];  // value
?>

数组元素的操作:

<?php
$arr = [5 => 1, 12 => 2];

$arr[] = 56;       // 自动分配下一个索引(13)
$arr["x"] = 42;    // 添加指定键的元素
unset($arr[5]);    // 删除键为 5 的元素
unset($arr);       // 删除整个数组
?>

索引数组

索引数组使用数字作为键,默认从 0 开始自动分配:

<?php
$cars = ["Porsche", "BMW", "Volvo"];
echo $cars[0];  // Porsche
echo count($cars);  // 3 —— 获取数组长度
?>

遍历索引数组:

<?php
$cars = ["Porsche", "BMW", "Volvo"];

// 方式一:for 循环
for ($i = 0; $i < count($cars); $i++) {
    echo $cars[$i] . "<br>";
}

// 方式二:foreach(推荐,更简洁)
foreach ($cars as $car) {
    echo "$car <br>";
}
?>

关联数组

关联数组使用自定义的字符串键名:

<?php
$age = ["Bill" => "63", "Steve" => "56", "Elon" => "47"];
echo "Elon is " . $age["Elon"] . " years old.";
?>

遍历关联数组,同时获取键和值:

<?php
$age = ["Bill" => "63", "Steve" => "56", "Elon" => "47"];

foreach ($age as $name => $ageValue) {
    echo "Key=$name, Value=$ageValue<br>";
}
?>

多维数组

多维数组是包含数组的数组,常见的是二维数组:

<?php
$cars = [
    ["Volvo", 22, 18],
    ["BMW", 15, 13],
    ["Saab", 5, 2],
    ["Land Rover", 17, 15],
];

echo $cars[0][0] . ": 库存:" . $cars[0][1] . ", 销量:" . $cars[0][2];
// Volvo: 库存:22, 销量:18
?>

遍历二维数组使用嵌套循环:

<?php
for ($row = 0; $row < count($cars); $row++) {
    echo "<b>第 $row 行</b>";
    for ($col = 0; $col < count($cars[$row]); $col++) {
        echo $cars[$row][$col] . " ";
    }
}
?>

数组排序

PHP 提供了丰富的数组排序函数:

函数排序方式说明
sort()升序对索引数组按值升序排列,重建索引
rsort()降序对索引数组按值降序排列,重建索引
asort()升序对关联数组按值升序,保留键名
arsort()降序对关联数组按值降序,保留键名
ksort()升序对关联数组按键升序
krsort()降序对关联数组按键降序
<?php
$numbers = [3, 5, 1, 22, 11];
sort($numbers);    // [1, 3, 5, 11, 22]
rsort($numbers);   // [22, 11, 5, 3, 1]

$age = ["Bill" => "63", "Steve" => "56", "Elon" => "47"];
asort($age);       // 按年龄升序
ksort($age);       // 按名字字母升序
?>
sort()rsort() 会重新生成数字索引——如果你需要保留键名(关联数组),务必使用 asort() / arsort() / ksort() / krsort()

一句话小结

数组是 PHP 最核心的数据结构:索引数组配合 for 遍历,关联数组配合 foreach 遍历,多维数组用嵌套循环。排序用 sort 家族函数,关联数组记得用 asort 系列保留键名。下一篇讲 超全局变量

最后更新于