PHP - 合并两个数组类似array_combine,但有重复键 [英] PHP - merge two arrays similar to array_combine, but with duplicate keys
本文介绍了PHP - 合并两个数组类似array_combine,但有重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组:
$arrKeys = array('str', 'str', 'otherStr');
$arrVals = array('1.22', '1.99', '5.17');
我想将它们合并到这样的事情
I would like to merge them into something like this
$arrResult = array(
array('str' => 1.22),
array('str' => 1.99),
array('otherStr' => 5.17)
);
键是不唯一的,否则我会使用 array_combine
。这将使有点不同的输出,但它适合我的。
The keys are non-unique, otherwise I'd use array_combine
. That would give a bit different output, but it would suit me as well.
这能在一个优雅的方式使用PHP 5.2.x完成,无需的foreach
/ 为
循环,preferably使用PHP的内置函数?
Can this be done in an elegant way using PHP 5.2.x, without foreach
/for
loops, preferably using PHP's built-in functions?
推荐答案
您可以使用 array_map
:
You can use array_map
:
$arrKeys = array('str', 'str', 'otherStr');
$arrVals = array('1.22', '1.99', '5.17');
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $arrKeys, $arrVals);
print_r($arrResult);
Array
(
[0] => Array
(
[str] => 1.22
)
[1] => Array
(
[str] => 1.99
)
[2] => Array
(
[otherStr] => 5.17
)
)
顺便说一句,如果升级到PHP 5.3,可以使用匿名函数,这是一个比较优雅的做到这一点:
BTW, if you upgrade to PHP 5.3 you can do this using an anonymous function, which is a bit more elegant:
array_map(function($key, $val) {return array($key=>$val);}, $arrKeys, $arrVals);
这篇关于PHP - 合并两个数组类似array_combine,但有重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文