php array实现
PHP 数组实现
PHP 数组是一种灵活的数据结构,可以存储多个值。以下是几种常见的实现方式:
索引数组 索引数组使用数字作为键名,默认从0开始递增。
$fruits = array("Apple", "Banana", "Orange");
// 或
$fruits = ["Apple", "Banana", "Orange"];
关联数组 关联数组使用字符串作为键名,建立键值对关系。
$person = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
// 或
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
多维数组 多维数组包含一个或多个数组作为元素。
$employees = array(
array("name" => "John", "age" => 30),
array("name" => "Jane", "age" => 25),
array("name" => "Doe", "age" => 35)
);
数组操作
添加元素
使用[]或array_push()函数向数组添加元素。
$fruits[] = "Grape";
array_push($fruits, "Mango");
删除元素
使用unset()函数删除数组中的元素。
unset($fruits[1]); // 删除第二个元素
遍历数组
使用foreach循环遍历数组。
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
关联数组遍历 可以同时获取键和值。
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
常用数组函数
count() 获取数组长度。
echo count($fruits); // 输出数组元素个数
array_merge() 合并两个或多个数组。
$combined = array_merge($fruits, ["Peach", "Pear"]);
array_search() 在数组中搜索给定的值并返回键名。
$key = array_search("Banana", $fruits);
sort() 对数组进行升序排序。
sort($fruits);
rsort() 对数组进行降序排序。
rsort($fruits);
ksort() 根据键名对关联数组进行升序排序。
ksort($person);
asort() 根据值对关联数组进行升序排序。
asort($person);
PHP数组功能强大,支持多种操作和函数,可以根据需求灵活使用。





