将两个数组合并为 PHP 中的键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/162032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge two arrays as key value pairs in PHP
提问by aib
I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.
我有两个相同大小的数组。我想合并两者,这样一个的值是新数组的关键索引,新数组的值是另一个的值。
Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?
现在我只是循环遍历数组并手动创建新数组,但我觉得有一种更优雅的方法来解决这个问题。我没有看到任何用于此目的的数组函数,但也许我错过了什么?有没有一种简单的方法可以做到这一点?
$mapped_array = mapkeys($array_with_keys, $array_with_values);
回答by aib
See array_combine()on PHP.net.
请参阅array_combine()PHP.net。
回答by Christopher Lightfoot
(from the docs for easy reading)
(来自文档以便于阅读)
array_combine — Creates an array by using one array for keys and another for its values
array_combine — 通过使用一个数组作为键和另一个作为其值的数组来创建一个数组
Description
描述
array array_combine ( array $keys , array $values )
array array_combine ( array $keys , array $values )
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
通过使用keys数组中的值作为键和values数组中的值作为对应的值来创建一个数组。
Parameters
参数
keys - Array of keys to be used. Illegal values for key will be converted to string.
keys - 要使用的键数组。键的非法值将被转换为字符串。
values - Array of values to be used
values - 要使用的值数组
Example
例子
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
The above example will output:
上面的例子将输出:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
回答by Mathias
This should do the trick
这应该可以解决问题
function array_merge_keys($ray1, $ray2) {
$keys = array_merge(array_keys($ray1), array_keys($ray2));
$vals = array_merge($ray1, $ray2);
return array_combine($keys, $vals);
}

