合并2个数组行(总和2个值)

时间:2013-11-18 13:04:04

标签: php arrays merge

我有这个数组:

array(
    array('id' => 1, 'price' => 20.00, 'stock' => 2, 'year' => 11 ),
    array('id' => 1, 'price' => 20.00, 'stock' => 3, 'year' => 12 ),
    array('id' => 1, 'price' => 20.00, 'stock' => 2, 'year' => 13 ),
    array('id' => 2, 'price' => 36.00, 'stock' => 11, 'year' => 13 ),
);

当id相同(同一篇文章)且年份为12 AND 13时,我需要将“stock”列相加。

结果应为:

array(
    array('id' => 1, 'price' => 20.00, 'stock' => 2, 'year' => 11 ),
    array('id' => 1, 'price' => 20.00, 'stock' => 5, 'year' => 13 ),
    array('id' => 2, 'price' => 36.00, 'stock' => 11, 'year' => 13 ),
);

注意'year'=>已删除12并且该行的库存已添加到13行。

如果没有用一堆bucles创建一大堆spaguetti代码,我就无法做到这一点。也许以更干净的方式有一个PHP功能?

抱歉我的英文。

2 个答案:

答案 0 :(得分:3)

如果您坚持使用PHP而不是数据库解决此问题,那么这将解决问题:

function group_sum($array) 
{
    $return = array();

    foreach ($array as $v)
    {
        $key = $v['id'] . '_' . ($v['year'] == 12 ? 13 : $v['year']);

        if (array_key_exists($key, $return))
        {
            $return[$key]['stock'] += $v['stock'];

            if ($v['year'] > $return[$key]['year'])
                $return[$key]['year'] = $v['year'];
        }
        else
        {
            $return[$key] = $v;
        }
    }

    return $return;
}

答案 1 :(得分:0)

我尝试到达这里......请任何人都可以推动这些代码......

$ary = array(
  array('id' => 1, 'price' => 20.00, 'stock' => 8, 'year' => 11 ),
  array('id' => 1, 'price' => 20.00, 'stock' => 3, 'year' => 12 ),
  array('id' => 1, 'price' => 20.00, 'stock' => 2, 'year' => 13 ),
  array('id' => 2, 'price' => 36.00, 'stock' => 11, 'year' => 13 ),
);

$ary2 = $ary;
$i=0;
foreach($ary as $row){

foreach($ary2 as $row2){
    if($row['id']==$row2['id'] && $row['year'] > $row2['year']){
        $ary[$i]['stock'] = $row['stock'] + $row2['stock'];
        unset($row);
    }   
}
//
$i++;
}
echo "<pre/>";
print_r($ary);