如何分组和求和多维数组?

时间:2014-06-04 08:33:14

标签: php multidimensional-array group-by sum

我已经看过this stackoverflow page,但它没有帮助我。

我希望按两列分组并对第三列的值求和。

如果discount_iddis_percent相同,则添加discount_value

这是我的阵列:

$dis = [
    [['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '7.500'], ['Dis_val' => '192.75']],
    [['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '97.88']],
    [['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '5.000'], ['Dis_val' => '39.90']],
    [['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '99.90']]
];

我需要的输出是:

D1-Dis1->7.5->192.75
D1-Dis1->5.0->39.9
D1-Dis2->2.5->197.78

我的代码如下所示:

$newarr = array();
$reverse_map = array();

foreach($dis as $idx => $entry) {
    if (isset($reverse_map[$entry['Dis_id']])) {
         // have we seen this name before? retrieve its original index value
         $idx = $reverse_map[$entry['Dis_id']]; 
    } else {
         // nope, new name, so store its index value
         $reverse_map[$entry['Dis_id']] = $idx;
    }

    // copy the 'constant' values
    $newarr[$idx]['Dis_id'] = $entry['Dis_id'];
    $newarr[$idx]['Dis_per'] = $entry['Dis_per'];

    // sum the qtd_post values to whatever we previously stored.        
    foreach($entry['Dis_val'] as $x => $y) {
        $newarr[$idx]['Dis_val'][$x] += $y;
    }
}

2 个答案:

答案 0 :(得分:2)

这是我提出的解决方案,基于您对预期阵列结构的理解;

$dis = array(
    array(
        'Dis_id'  => 'Dl-Dis1',
        'Dis_per' => 7.500,
        'Dis_val' => 192.75
    ),
    ...
);

它通过创建多维数组来确定解决方案,其中第一个维度为Dis_id,第二个维度为Dis_per,值为Dis_val的总和;

$sums = array();

foreach ($dis as $entry) {
    if (!isset($sums[$entry['Dis_id']])) {
        $sums[$entry['Dis_id']] = array();
    }
    if (!isset($sums[$entry['Dis_id']]["{$entry['Dis_per']}"])) {
        $sums[$entry['Dis_id']]["{$entry['Dis_per']}"] = 0;
    }
    $sums[$entry['Dis_id']]["{$entry['Dis_per']}"] += $entry['Dis_val'];
}

见这个工作实例; https://eval.in/158661

答案 1 :(得分:0)

迭代输入数组时,需要隔离Dis_idDis_per值,并在存储Dis_val时将它们用作键。

如果[Dis_id][Dis_per]元素不存在任何值,则可以简单地存储该值。如果存在一个预先存在的值,则需要将新值添加到存储的值中。 isset()是最有效的功能,可帮助识别结果数组中的新元素/现有元素。

代码:(Demo

$dis = [
    [['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '7.500'], ['Dis_val' => '192.75']],
    [['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '97.88']],
    [['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '5.000'], ['Dis_val' => '39.90']],
    [['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '99.90']]
];

foreach ($dis as $group) {
    $id = $group[0]['Dis_id'];
    $per = $group[1]['Dis_per'];
    if (!isset($result[$id][$per])) {
        $result[$id][$per] = $group[2]['Dis_val'];
    } else {
        $result[$id][$per] += $group[2]['Dis_val'];
    }
}
var_export($result);

输出:

array (
  'Dl-Dis1' => 
  array (
    '7.500' => '192.75',
    '5.000' => '39.90',
  ),
  'Dl-Dis2' => 
  array (
    '2.500' => 197.78,
  ),
)