这是我的阵列:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
这是我的另一个数组
array
0 =>
array
'entity_id' => 1
'order_status' => 'test'
1 =>
array
'entity_id' => 2
'order_status' => 'test2'
我的目标是实现这个目标:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
'entity_id' => 1
'order_status' => 'test'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
'entity_id' => 2
'order_status' => 'test2'
使用array_merge我设法得到了这个(不是我想要的目标),这就是我在stackoverflow和其他论坛上找到的所有内容:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
array
2 =>
array
'entity_id' => 1
'order_status' => 'test'
3 =>
array
'entity_id' => 2
'order_status' => 'test2'
欢迎任何想法或建议:)谢谢
使用foreach我可以添加键值,但我正在寻找更干净的方法:)
答案 0 :(得分:1)
需要注意的是,你的数组没有一个联合值可以比较,所以你需要确保键总是排成一行,我认为像这样的循环可以解决这个问题:
for ($i = 0; $i < count($array1); $i++)
{
$new_array[] = array_merge($array1[$i], $array2[$i]);
}
编辑:您也可以使用array_map()
,但它不会提供AFAIK的任何性能优势,并且总体上不太可读。
$new_array = array_map(function($a1_v, $a2_v) { return array_merge($a1_v, $a2_v); }, $a1, $a2);
答案 1 :(得分:1)
以下是array_map和array_merge_recursive对您问题的回答。
<?php
$array1 = array(
[
"id" => 220950,
"order_reference" => "600125479"
],
[
"id" => 220985,
"order_reference" => "498638"
]
);
$array2 = array(
[
"entity_id" => 1,
"order_status" => "test"
],
[
"entity_id" => 2,
"order_status" => "test"
]
);
$results = array();
array_map(function($array1, $array2) use (&$results) {
$results[] = array_merge_recursive($array1, $array2);
}, $array1, $array2);
var_dump($results);
这将输出:
array (size=2)
0 =>
array (size=4)
'id' => int 220950
'order_reference' => string '600125479' (length=9)
'entity_id' => int 1
'order_status' => string 'test' (length=4)
1 =>
array (size=4)
'id' => int 220985
'order_reference' => string '498638' (length=6)
'entity_id' => int 2
'order_status' => string 'test' (length=4)
答案 2 :(得分:1)
将 array_merge 与 array_map
一起使用 $array1 = array(
[
"id" => 220950,
"order_reference" => "600125479"
],
[
"id" => 220985,
"order_reference" => "498638"
]
);
$array2 = array(
[
"entity_id" => 1,
"order_status" => "test"
],
[
"entity_id" => 2,
"order_status" => "test2"
]
);
$result = array_map("array_merge",$array1,$array2);
print_r($result);
输出
Array
(
[0] => Array
(
[id] => 220950
[order_reference] => 600125479
[entity_id] => 1
[order_status] => test
)
[1] => Array
(
[id] => 220985
[order_reference] => 498638
[entity_id] => 2
[order_status] => test2
)
)
工作example