在php foreach中按日期分组数组项目

时间:2015-03-10 13:09:15

标签: php arrays date foreach grouping

我在php中有如下数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [time] => 2014-11-09T16:32:05
            [power] => 0.123
        )
    [1] => Array
        (
            [id] => 2
            [time] => 2014-11-19T18:32:06
            [power] => 0.208
        )
    [2] => Array
        (
            [id] => 3
            [time] => 2013-09-19T20:32:07
            [power] => 0.106
        ) 
    [3] => Array
        (
            [id] => 4
            [time] => 2013-09-20T10:32:07
            [power] => 0.248
        ) 
    [4] => Array
        (
            [id] => 5
            [time] => 2013-09-20T12:32:07
            [power] => 0.298
        ) 
)

我想计算以下算法产生的每天的电力消耗

for(i = 0; i < array.lengh - 1; i++){ 
 $power = array.data[i].power; 
 $time_diff = (array.data[i+1].time)/(1000*60*60) - array.data[i].time)/(1000*60*60)); 

 $consumption .= $power * $time_diff; 
} 

如何在php中执行此操作,每天对$consumption进行分组?

1 个答案:

答案 0 :(得分:3)

您可以在此处使用PHP强大的strtotime()功能。这为您提供了一个unix时间戳,您可以更好地使用它。要回答您的问题,可以通过以下方式完成

$sortedData = array();
foreach ($data as $element) {
    $timestamp = strtotime($element['time']);
    $date = date("d.m.Y", $timestamp); //truncate hours:minutes:seconds
    if ( ! isSet($sortedData[$date]) ) { //first entry of that day
        $sortedData[$date] = array($element);
    } else { //just push current element onto existing array
        $sortedData[$date][] = $element
    }
}

这应该以

的形式给你一个新的数组
Array(
    ['19.09.2013'] => Array(
        [0] => Array([id] => ..., [time] => ..., [power] => ...),
        [1] => Array([id] => ..., [time] => ..., [power] => ...),
        ...
    ),
    ['20.09.2013'] => Array(
        [0] => Array([id] => ..., [time] => ..., [power] => ...),
        [1] => Array([id] => ..., [time] => ..., [power] => ...),
        ...
    ),
    ...
)

要获得权力的总和,只需做类似的事情

foreach ($sortedData as $date=>$elements) {
    $sum = 0;
    foreach ($elements as $element) {
        $sum += $element['power'];
    }
    echo "The total sum for $date is $sum.";
}