我有两个阵列
$companyA[] = array ("QuantityOnOrder" => $quantityOnOrder, "QuantityOnHand" => $quantityOnHand, "Name" => $name);
$companyB[] = array ("QuantityOnOrder" => $quantityOnOrder, "QuantityOnHand" => $quantityOnHand, "Name" => $name);
这些是多维数组。假设A公司有3个记录,B公司有10个记录。让我们进一步假设companya中的一个记录与companyb中的一个记录共享相同的“name”属性。如果这是真的,那么我想从每个数组中获取quantityonorder和quantityonhand,并添加它们的值并将它们存储在一个新数组中。
然后,我还要确保这个新数组同时具有两个数组中的所有唯一值。下面是一个数组的外观示例,以及我希望最终结果的外观示例。
公司:
Array (
[0] => Array ([QuantityOnHand] => 10 [QuantityOnOrder] => 20 [Name] => LOR1)
[1] => Array ([QuantityOnHand] => 5 [QuantityOnOrder] => 6 [Name] => D23-72-P)
[2] => Array ([QuantityOnHand] => 2331 [QuantityOnOrder] => 0 [Name] => RB)
[3] => Array ([QuantityOnHand] => 3520 [QuantityOnOrder] => 0 [Name] => RTOP))
公司B:
Array (
[0] => Array ([QuantityOnHand] => 11 [QuantityOnOrder] => 13 [Name] => RPEN)
[1] => Array ([QuantityOnHand] => 5 [QuantityOnOrder] => 6 [Name] => D23-72-P)
[2] => Array ([QuantityOnHand] => 23 [QuantityOnOrder] => 0 [Name] => RAT)
[3] => Array ([QuantityOnHand] => 320 [QuantityOnOrder] => 0 [Name] => RBOT))
组合阵列:
Array (
[0] => Array ([QuantityOnHand] => 10 [QuantityOnOrder] => 20 [Name] => LOR1)
[1] => Array ([QuantityOnHand] => 10 [QuantityOnOrder] => 12 [Name] => D23-72-P)
[2] => Array ([QuantityOnHand] => 2331 [QuantityOnOrder] => 0 [Name] => RB)
[3] => Array ([QuantityOnHand] => 3520 [QuantityOnOrder] => 0 [Name] => RTOP))
[4] => Array ([QuantityOnHand] => 11 [QuantityOnOrder] => 13 [Name] => RPEN)
[5] => Array ([QuantityOnHand] => 23 [QuantityOnOrder] => 0 [Name] => RAT)
[6] => Array ([QuantityOnHand] => 320 [QuantityOnOrder] => 0 [Name] => RBOT))
请注意,在组合数组中,我有来自companya和companyb的所有记录,并且共享相同名称的记录已经组合。希望这对某人来说足够有意义。我无法找到在组合数组中实现所需结果的最佳方法。任何帮助都将不胜感激。
最佳答案
我认为如果这是一个关联数组,键是数组的名称和值,那么这可能更容易。
否则,我将首先索引数组,以防止在必要时出现更多循环。这是未经测试的,但也许你可以尝试一下。
$i = 0;
foreach($company_a as $a) {
$idx_a[$a['Name']] = $i++;
}
$i = 0;
foreach($company_a as $b) {
$idx_b[$b['Name']] = $i++;
}
$toMerge = array_filter($company_b, function($value) {
return array_key_exists($value['Name'], $idx_a);
});
$toRemove = array();
foreach($toMerge as $m) {
$i = $idx_a[$m['Name']];
$c = $company_a[$i];
$company_a[$i]['QuantityOnHand'] = $c['QuantityOnHand'] + $m['QuantityOnHand'];
$company_a[$i]['QuantityOnOrder'] = $c['QuantityOnOrder'] + $m['QuantityOnOrder'];
$toRemove[] = $idx_b[$m['Name']];
}
foreach($toRemove as $i) {
unset($company_b[$]);
}
//company_a now has the final result
$company_a = array_merge($company_a, $company_b);