📅  最后修改于: 2023-12-03 15:17:12.318000             🧑  作者: Mango
Laravel 提供了一个集合(Collection)类,可以方便地处理数组数据。其中,combine()
方法可以将两个数组合并为一个关联数组,其中一个数组作为键,另一个数组作为值。
$keys = ['name', 'email', 'phone'];
$values = ['John Doe', 'johndoe@example.com', '123-456-7890'];
$combined = collect($keys)->combine($values);
print_r($combined);
输出:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[name] => John Doe
[email] => johndoe@example.com
[phone] => 123-456-7890
)
)
上述代码中,我们将 $keys
数组作为键,$values
数组作为值,通过 collect()
方法将它们封装成集合对象,然后调用 combine()
方法得到一个关联数组。
combine()
方法要求两个数组的元素个数必须相等,否则将会抛出异常。