PHP array_combine 函数
最后修改于 2025 年 3 月 13 日
PHP array_combine 函数通过使用一个数组作为键,另一个数组作为值来创建一个数组。这对于配对相关数据非常有用。
基本定义
array_combine 函数将两个数组合并成一个关联数组。第一个数组提供键,第二个数组提供对应的值。
语法:array_combine(array $keys, array $values): array。两个数组的元素数量必须相等。返回新的关联数组。
array_combine 基本示例
这展示了如何将简单的键和值数组合并成一个关联数组。
basic_array_combine.php
<?php $keys = ['name', 'age', 'city']; $values = ['Alice', 25, 'New York']; $combined = array_combine($keys, $values); print_r($combined);
这会将字符串键与混合值组合。生成的数组使用 $keys 作为键,$values 作为相应的、按相同顺序排列的值。
合并数字数组
演示如何合并数字数组以创建一个关联数组。
numeric_arrays.php
<?php $ids = [101, 102, 103]; $names = ['Product A', 'Product B', 'Product C']; $products = array_combine($ids, $names); print_r($products);
这里数字 ID 成为数组键,与产品名称配对。请注意,数组键在 PHP 关联数组中可以是整数。
错误处理
展示当不同大小的数组合并时会发生什么。
error_handling.php
<?php
$keys = ['a', 'b', 'c'];
$values = [1, 2];
try {
$result = array_combine($keys, $values);
print_r($result);
} catch (ValueError $e) {
echo "Error: " . $e->getMessage();
// Output: Error: array_combine(): Argument #2 ($values) must have the same number of elements as argument #1 ($keys)
}
当数组大小不同时,该函数会抛出一个 ValueError。在合并数组之前,始终确保数组具有相同的长度。
与数组函数结合使用
演示如何将 array_combine 与其他数组函数(如 array_map)一起使用。
with_functions.php
<?php
$headers = ['ID', 'NAME', 'PRICE'];
$data = ['101', 'Widget', '19.99'];
// Convert headers to lowercase keys
$keys = array_map('strtolower', $headers);
$combined = array_combine($keys, $data);
print_r($combined);
这在组合之前将标题转换为小写。array_map 函数修改键数组,然后再在 array_combine 中使用。
真实的 CSV 示例
展示了将 CSV 数据处理成关联数组的实用示例。
csv_example.php
<?php
$csvData = [
['id', 'name', 'email'],
[1, 'John Doe', 'john@example.com'],
[2, 'Jane Smith', 'jane@example.com']
];
$headers = array_shift($csvData); // Get headers
$result = [];
foreach ($csvData as $row) {
$result[] = array_combine($headers, $row);
}
print_r($result);
这会将类似 CSV 的数据处理成一个关联数组的数组。每一行都与标题组合,以创建有意义的键-值对。
最佳实践
- 长度相等: 始终验证数组具有相同数量的元素。
- 有效键: 确保键有效(字符串或整数)。
- 数据对齐: 确认值与正确的键对应。
- 错误处理: 对生产代码使用 try-catch。
来源
本教程介绍了 PHP array_combine 函数,并提供了实用示例,展示了如何使用它从单独的键和值数组创建关联数组。
作者
列出 所有 PHP 数组函数。