我有两个数组:
$a = [
0 => [
'price' => 5.5
],
1 => [
'price' => 6.0
],
2 => [
'price' => 6.2
],
3 => [
'price' => 6.5
],
];
$b = [
0 => [
'color' => 'RED'
],
1 => [
'color' => 'WHITE'
],
2 => [
'color' => 'BLUE'
],
3 => [
'color' => 'RED'
],
];
我应该有这样的回应:
Array
(
[0] => Array
(
[price] => 5.5
[color] => RED
)
[1] => Array
(
[price] => 6
[color] => WHITE
)
[2] => Array
(
[price] => 6.2
[color] => BLUE
)
[3] => Array
(
[price] => 6.5
[color] => RED
)
)
我听说过函数:array_merge_recursive但响应并不是必须的:
Array
(
[0] => Array
(
[price] => 5.5
)
[1] => Array
(
[price] => 6
)
[2] => Array
(
[price] => 6.2
)
[3] => Array
(
[price] => 6.5
)
[4] => Array
(
[color] => RED
)
[5] => Array
(
[color] => WHITE
)
[6] => Array
(
[color] => BLUE
)
[7] => Array
(
[color] => RED
)
)
所以我决定编写自己的函数:
function merge ($a, $b) {
$keys = array_keys($a);
foreach ($keys as $value) {
if (isset($b[$value])) {
$tmp = array_keys($b[$value]);
foreach ($tmp as $val){
$a[$value][$val] = $b[$value][$val];
}
}
}
return $a;
}
print_r(merge($a, $b));
我得到了正确的答复:
Array
(
[0] => Array
(
[price] => 5.5
[color] => RED
)
[1] => Array
(
[price] => 6
[color] => WHITE
)
[2] => Array
(
[price] => 6.2
[color] => BLUE
)
[3] => Array
(
[price] => 6.5
[color] => RED
)
)
问题是它适用于小型阵列,但对大型阵列不起作用,所以我的问题是:我怎样才能优化这个功能?因为复杂性会增加,具体取决于合并的密钥。
使用PHP 7.0
答案 0 :(得分:4)
您需要检查它们的长度是否相同,然后只需要一个简单的foreach
:
foreach($a as $k => $v) {
$result[$k] = array_merge($v, $b[$k]);
}
答案 1 :(得分:4)
答案 2 :(得分:0)
简单的解决方案可能是,
$c = [];
for($i=0; $i<count(array_keys($a)); $i++) {
$c[$i] =array_merge($a[$i], $b[$i]);
}
print_r($c);