我有以下数组:
Array
(
[0] => Array
(
[Import] => Array
(
[id] => 1
[category_id] => 2
[product_id] => 2
[amount] => 50
[cost] => 8320
[comment] => transportation and others cost: 100
[created] => 2015-06-23 19:21:10
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[1] => Array
(
[Import] => Array
(
[id] => 2
[category_id] => 2
[product_id] => 2
[amount] => 15
[cost] => 3000
[comment] =>
[created] => 2015-06-22 18:10:36
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[2] => Array
(
[Import] => Array
(
[id] => 3
[category_id] => 2
[product_id] => 1
[amount] => 15
[cost] => 2000
[comment] =>
[created] => 2015-06-23 19:20:15
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 0
[confirmed] => 0
[canceled] => 0
)
)
)
我想在[Import] [product_id]中删除相同product_id的重复值,但要求sum [Import] [amount]。我期望的数组是:
Array
(
[0] => Array
(
[Import] => Array
(
[id] => 1
[category_id] => 2
[product_id] => 2
[amount] => 65
[cost] => 8320
[comment] => transportation and others cost: 100
[created] => 2015-06-23 19:21:10
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[1] => Array
(
[Import] => Array
(
[id] => 3
[category_id] => 2
[product_id] => 1
[amount] => 15
[cost] => 2000
[comment] =>
[created] => 2015-06-23 19:20:15
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 0
[confirmed] => 0
[canceled] => 0
)
)
)
如果有人提供解决此问题的功能,这将是一个真正的礼物。
答案 0 :(得分:1)
$filteredArray = [];
foreach ($array as $productData) {
if (isset($filteredArray[$productData['Import']['product_id']])) {
$filteredArray[$productData['Import']['product_id']]['Import']['amount'] += $productData['Import']['amount'];
}
else {
$filteredArray[$productData['Import']['product_id']] = $productData;
}
}
print_r($filteredArray);
啊..忘了提 - - $array
是你的基础数组。
答案 1 :(得分:0)
/**
* Removes duplicate summing amount from products array
*
* @param array $array
* @return array
*/
function removeDuplicates($array)
{
$idsCount = array();
foreach ($array as $key => $value) {
$idsCount[$value['Import']['product_id']]['count'] += 1;
$idsCount[$value['Import']['product_id']]['sum'] += $value['Import']['amount'];
if ($idsCount[$value['Import']['product_id']]['count'] > 1) {
unset($array[$key]);
$array[$idsCount[$value['Import']['product_id']]['key']]['Import']['amount'] = $idsCount[$value['Import']['product_id']]['sum'];
} else {
$idsCount[$value['Import']['product_id']]['key'] = $key;
}
}
return $array;
}
我知道它看起来很疯狂,但是在您的特定阵列上格式化。