我有2个阵列:
数组1包含2个产品。
[records] => Array
(
[0] => Array
(
[productID] => 3347
[amountInStock] => 2.000000
)
[1] => Array
(
[productID] => 6798
[amountInStock] => 1.000000
)
)
数组2包含3个产品。一个产品也在阵列中
[records] => Array
(
[0] => Array
(
[productID] => 3347
[amountInStock] => 0
)
[1] => Array
(
[productID] => 6332
[amountInStock] => 1.000000
)
[2] => Array
(
[productID] => 6922
[amountInStock] => 3.000000
)
)
现在我需要将2个数组合并到像这样的表
product | array 1 | array 2
3347 2 0
6798 1 0
6332 0 0
6922 0 2
我该怎么办
答案 0 :(得分:1)
使用foreach
并将元素添加到新数组中。
$new = [];
foreach ($array1 as $element) {
if (isset($new[$element['productID']])) {
$new[$element['productID']]['array 1'] = $element['ammountInStock'];
} else {
$new[$element['productID']]['array 1'] = $element['ammountInStock'];
$new[$element['productID']]['array 2'] = 0;
}
}
foreach ($array1 as $element) {
if (isset($new[$element['productID']])) {
$new[$element['productID']]['array 2'] = $element['ammountInStock'];
} else {
$new[$element['productID']]['array 2'] = $element['ammountInStock'];
$new[$element['productID']]['array 1'] = 0;
}
}
答案 1 :(得分:1)
完成所需内容的另一种方法是使用array_merge()。
<?php
$arr1 = array(
array('productID' => 3347,
'amountInStock' => 2.000000
),
array('productID' => 6798,
'amountInStock' => 1.000000
)
);
$arr2 = array(
array('productID' => 6332,
'amountInStock' => 3.000000
),
array('productID' => 6330,
'amountInStock' => 4.000000
)
);
$arr = array_merge($arr1, $arr2);
var_dump($arr);
?>
编辑: 如果您想防止重复输入,请尝试使用array_unique()。