php - 如何将两个不同的数组合并到一个上
问题描述
如果您已经有相同的 ID,或者如果您没有创建新对象,如何更新对象数组、添加数量。
我试图在代码中解释数组以及我希望结果如何的想法。
旧数组
$a1 = [
array(
"id" => 1,
"qty" => 1
),
array(
"id" => 2,
"qty" => 1
)
];
$a2 = [
array(
"id" => 1,
"qty" => 1
)
];
$output = array_merge($a1, $a2);
echo '<pre>';
print_r($output);
echo '</pre>';
结果错误:
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
)
[1] => Array
(
[id] => 2
[qty] => 1
)
[2] => Array
(
[id] => 1
[qty] => 1
)
)
我需要什么,除了如果ID不包含,添加。
Array
(
[0] => Array
(
[id] => 1
[qty] => 2
)
[1] => Array
(
[id] => 2
[qty] => 1
)
)
解决方案
您可以将第一个数组作为基础,然后搜索product
与id
. 然后添加数量并重新计算价格,或者您只需添加重新格式化的元素(id
转换product
)。
$result = $a;
foreach($b as $element) {
$matchingProductIndex = array_search($element['id'], array_column($a, 'product'));
if ($matchingProductIndex !== false) {
$pricePerUnit = $result[$matchingProductIndex]['price'] / $result[$matchingProductIndex]['qty'];
$result[$matchingProductIndex]['qty'] += $element['qty'];
$result[$matchingProductIndex]['price'] = $result[$matchingProductIndex]['qty'] * $pricePerUnit;
} else {
$result[] = [
'qty' => $element['qty'],
'product' => $element['id'],
'price' => $element['price'],
];
}
}
print_r($result);
工作示例。
推荐阅读
- c - 线程 1:EXC_BAD_ACCESS (code=1, address=0x0) 内存分配
- jupyter-notebook - 从 jupyter notebook 获取交互滑块以在 bokeh html 文件中工作
- linphone - 如何处理 linphone 中的 dtmf
- javascript - 如何检查哪个组件称为 primefaces remoteCommand?
- string - 当程序要求输入数字时,防止用户输入字母的最简单方法是什么?
- angular - 从 Angular 6 升级到 8 后,Angular 8 ng 服务未加载应用程序
- css - css变量中的计算不起作用
- scala - 广播不会输出 Akka Streams
- python - 为什么 BeautifulSoup 不返回子元素?
- node.js - 无法启动 React 项目