开发者

PHP Array addition on matching elements

I need a function that can add the elements of x arrays that have matching elements.

Here is an example of a source array with two elements.

Array
(
    [0] => Array
        (
            [0] => Array
                ([kwh] => 313.9799,[time_read] => 1311825600)

            [1] => Array
                ([kwh] => 312.3098,[time_read] => 1311826500)

            [2] => Array
                ([kwh] => 302.0525,[time_read] => 1311827400)

            [3] => Array
                ([kwh] => 312.2946,[time_read] => 1311828开发者_如何学编程300)
        )
    [1] => Array
        (
            [0] => Array
                ([kwh] => 723.4205,[time_read] => 1311825600)

            [1] => Array
                ([kwh] => 686.9258,[time_read] => 1311826500)

            [2] => Array
                ([kwh] => 714.3203,[time_read] => 1311827400)

            [3] => Array
                ([kwh] => 707.8232,[time_read] => 1311828300)
        )
)

And I'd like to see output like the following. What throws me is that the indexes of the arrays might not match up. One array might have 10 elements while the other might have 20. The time_read value has to be used to find matching array elements.

    Array
        (
            [0] => Array
                ([kwh] => 1036,[time_read] => 1311825600)

            [1] => Array
                ([kwh] => 998,[time_read] => 1311826500)

            [2] => Array
                ([kwh] => 1016,[time_read] => 1311827400)

            [3] => Array
                ([kwh] => 1019,[time_read] => 1311828300)
        )


Use the timestamp as an array key, use nested loops to grab the internal values and add them up

$output = array();
foreach ($source_array as $group) {
  foreach ($group as $a) {
    if (!isset($output[$a['time_read']]))
      $output[$a['time_read']] = array('time_read'=>$a['time_read'], 'kwh'=>0);
    $output[$a['time_read']]['kwh'] += $a['kwh'];
  }
}

print_r($output);
/* output

Array
    (
        [1311825600] => Array
            ([kwh] => 1036,[time_read] => 1311825600)

        [1311826500] => Array
            ([kwh] => 998,[time_read] => 1311826500)

        [1311827400] => Array
            ([kwh] => 1016,[time_read] => 1311827400)

        [1311828300] => Array
            ([kwh] => 1019,[time_read] => 1311828300)
    ) */

Also nice because then you can use ksort to order them chronologically

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜