数组项的总和 - php

时间:2014-09-17 12:19:35

标签: php arrays

我正在尝试将数组中的项目总和相加。

以下是数组中某些数据的副本。

$hours = Array ( 
[3] => 
    Array (
        [2014-09-15] => Array ( [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [21] => 2 [22] => 2 [23] => 2 [24] => 2 )
        [2014-09-16] => Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 2 ) 
        [2014-09-17] => Array ( [9] => 2 [10] => 2 [11] => 2 [12] => 2 [13] => 2 [14] => 2 [15] => 2 [16] => 2 ) 
        [2014-09-19] => Array ( [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1 [10] => 1 [11] => 1 [12] => 1 [13] => 1 [14] => 1 [15] => 1 [16] => 1 [17] => 1 [18] => 1 [19] => 1 [20] => 1 [21] => 1 [22] => 1 [23] => 1 [24] => 1 ) 
    )
 )

以下是我用来将它们添加到一起的代码。

$week_start_date = "2014-09-15";

for ( $i = 0; $i < 7; $i++ ) {
    $total_hours_day = date("Y-m-d", strtotime($week_start_date . "+ " . $i . " days"));
    $total_hours = array();
    foreach ( $hours as $the_user_id => $other_data1 ) {
        foreach ( $hours[$the_user_id][$total_hours_day] as $the_nth_hour => $other_data3 ){
            $total_hours[$the_nth_hour]++;
        }
    }
    echo $total_hours_day
    echo "<br />" . $total_hours["1"] . $total_hours["2"] . $total_hours["3"] . $total_hours["4"];
    echo "<br />" . $total_hours["5"] . $total_hours["6"] . $total_hours["7"] . $total_hours["8"];
    echo "<br />" . $total_hours["9"] . $total_hours["10"] . $total_hours["11"] . $total_hours["12"];
    echo "<br />" . $total_hours["13"] . $total_hours["14"] . $total_hours["15"] . $total_hours["16"];
    echo "<br />" . $total_hours["17"] . $total_hours["18"] . $total_hours["19"] . $total_hours["20"];
    echo "<br />" . $total_hours["21"] . $total_hours["22"] . $total_hours["23"] . $total_hours["24"];

}

有没有更简洁的方法来添加它?

我似乎也错过了我上一组数字中的$ total_hours [“24”]


1 个答案:

答案 0 :(得分:0)

试试这个:

$hours = Array ( 
[3] => 
    Array (
        [2014-09-15] => Array ( [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [21] => 2 [22] => 2 [23] => 2 [24] => 2 )
        [2014-09-16] => Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 2 ) 
        [2014-09-17] => Array ( [9] => 2 [10] => 2 [11] => 2 [12] => 2 [13] => 2 [14] => 2 [15] => 2 [16] => 2 ) 
        [2014-09-19] => Array ( [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1 [10] => 1 [11] => 1 [12] => 1 [13] => 1 [14] => 1 [15] => 1 [16] => 1 [17] => 1 [18] => 1 [19] => 1 [20] => 1 [21] => 1 [22] => 1 [23] => 1 [24] => 1 ) 
    )
 )

$total_hours = array();
$user_id = 3;

foreach($hours[$user_id] as $date => $work_hours){
   $total_hours[$user_id][$date] = array_sum($hours[$user_id][$date]);
}

print_r($total_hours);