tags:

views:

46

answers:

3

I have the following issue, I have an array with the name $data

Within this array I have something like

[6] => Array
        (
            [code] => 642
            [total] => 1708
        )

    [7] => Array
        (
            [code] => 642
            [total] => 53
        )

    [8] => Array
        (
            [code] => 642
            [total] => 1421
        )

In some elements the code value is the same, now what I want to do is merge all the elements with the same code value together, and adding the totals together. I tried doing this in a foreach loop, but does not seem to work.

I do something like this

$old_lc = null;
        $old_lcv = 0;
        $count = 0;
        $dd = null;


        foreach($data as $d){

            if($d['code'] == $old_lc){
                $d['total'] = $d['total'] + $old_lcv;
                $count--;
                $dd[$count]['code'] = $d['code'];
                $dd[$count]['total'] = $d['total'];

            }else{
                $dd[$count]['code'] = $d['code'];
                $dd[$count]['total'] = $d['total'];
                $count++;

            }

            $old_lc = $d['code'];
            $old_lcv = $d['total'];
        }

        $data = $dd;

But this does not seem to work. Also I need the $data array to keep the keys, and should remain in the same format

+3  A: 
  $result = array();
  foreach($ary as $elem) {
     $code = $elem['code'];
     $total = $elem['total'];
     if(!isset($result[$code]))
          $result[$code] = 0;
     $result[$code] += $total;
  }
stereofrog
+2  A: 

This code translates the above array into an array of code => total.

$out = array();
foreach ($data as $k => $v) {
  $out[$v['code']] += $v['total'];
}

It is worth noting that on certain settings this will generate a warning about undefined indexes. If this bothers you, you can use this alternate version:

$out = array();
foreach ($data as $k => $v) {
  if (array_key_exists($v['code'], $out)) {
    $out[$v['code']] += $v['total'];
  } else {
    $out[$v['code']] = $v['code'];
  }
}

This turns it back into something like the original, if that's what you want:

$output = array();
foreach ($out as $code => $total) {
  $output[] = array('code' => $code, 'total' => $total);
}

Note: the original keys of $data aren't maintained but it wasn't stated that this was a requirement. If it is, it needs to be specified how to reconstruct multiple elements that have the same code.

cletus
you should initialize $out elements before use. Notices are not good.
stereofrog
A: 
    [6] => Array
        (
            [code] => 642
            [total] => 1708
        )

    [7] => Array
        (
            [code] => 642
            [total] => 53
        )

    [8] => Array
        (
            [code] => 642
            [total] => 1421
        )

$data_rec = array();
$data = array();
foreach($data_rec as $key=>$rec)
{
   $data[$key]+= $rec[$key];
}
print_r($data);
krob