我有一个像这样的数组
Array ( [0] => Array ( [vendor_id] => 2 [vendor_total_order] => 80 ) [1] => Array ( [vendor_id] => 2 [vendor_total_order] => 100 ) [2] => Array ( [vendor_id] => 1 [vendor_total_order] => 150 ) [3] => Array ( [vendor_id] => 3 [vendor_total_order] => 80 ) [4] => Array ( [vendor_id] => 5 [vendor_total_order] => 150 ) [5] => Array ( [vendor_id] => 1 [vendor_total_order] => 110 ) )
我想以这样一种方式简化这个数组,如果' vendor_id'两个值相同,那里累积/总和值应分配给'vendor_total_order'到那个' vendor_id'(基本上我们正在删除具有相同vendor_id的值与重复项的总值)。
因此,当我提供上述数组作为输入时,输出应如下所示
Array ( [0] => Array ( [vendor_id] => 2 [vendor_total_order] => 180 ) [1] => Array ( [vendor_id] => 1 [vendor_total_order] => 260 ) [2] => Array ( [vendor_id] => 3 [vendor_total_order] => 80 ) [3] => Array ( [vendor_id] => 5 [vendor_total_order] => 150 ) )
我该怎么做?
答案 0 :(得分:1)
您只需要使用foreach对它们进行分组。例如:
$total = array();
foreach ($array as $key => $value) {
if(!isset($total[$value['vendor_id']])) {
$total[$value['vendor_id']] = array('vendor_id' => $value['vendor_id'], 'vendor_total_order' => 0);
}
$total[$value['vendor_id']]['vendor_total_order'] += $value['vendor_total_order'];
}
$total = array_values($total); // simple reindex
echo '<pre>';
print_r($total);
答案 1 :(得分:0)
最好的办法是编写一个执行以下操作的自定义脚本: