以七天为间隔显示平均读数

时间:2015-03-09 11:00:39

标签: php

给定一个数组,我需要显示每第七行后的平均值

Array
(
    [0] => Array
        (
            [date] => 01-03-2015
            [site_id] => 1
            [starting_reading] => 567
            [close_reading] => 567
        )

[1] => Array
    (
        [date] => 03-03-2015
        [site_id] => 1
        [starting_reading] => 567
        [close_reading] => 567

    )
[2] => Array
    (
        [date] => 08-03-2015
        [site_id] => 1
        [starting_reading] => 567
        [close_reading] => 567

    )
)

现在我需要的是在7天内显示所有平均读数,如:

1 to 7 
--------------------- avg=close-start----------
8 to 14
--------------------- avg=close-start----------
15 to 21
--------------------- avg=close-start----------
22 to 28
--------------------- avg=close-start----------
29 to 31 
--------------------- avg=close-start----------

date starting_reading close_reading

2015年1月3日

2015年3月3日

--------------------- avg = close-start ----------

2015年8月3日

--------------------- avg = close-start ----------

1 个答案:

答案 0 :(得分:0)

//$arr is as the array you described
foreach($arr as $k => $v){
  //$k will be some integer 0...count($arr)-1 assuming a 'normal' index
  //$v is your child array, where you can access attributes such as $v['date']
  //every seventh row can be done in a number of ways, the easiest way is:
  if($k % 7 == 0){
    //then show new line. This will happen every time the number divides into seven. 0, 7, 14, 21... etc.
    var_dump($v); will output your child of the seventh (multiple) item
  }
}

包括假设数组格式正确的日期和平均值的示例

//$arr is as the array you described
$close = 0;
$start = 0;
foreach($arr as $k => $v){
  //$k will be some integer 0...count($arr)-1 assuming a 'normal' index
  //$v is your child array, where you can access attributes such as $v['date']
  //every seventh row can be done in a number of ways, the easiest way is:
  if($k % 7 == 0){
    $close = 0; //reset close
    $start = 0; //reset start
  }
  $close += (int)$v['close_reading'];
  $start += (int)$v['starting_reading'];
  if(($k + 1) % 7 == 0){ //this is the last row, 6, 13, 20 etc.
    echo ($k-5).' to '.($k+1);
    echo 'Average: '.(($close - $start) / 7);
  }
}