簡體   English   中英

如何對數組中的值求和

[英]How to sum values from an array

我正在嘗試對數據庫中的所有SELECT COUNT求和,以獲得員工的總工作時間。 $theWeek包含時間戳格式的當前星期幾, $vendeur是從 HTML 和 JS 中獲取的員工 ID。

這就是我在print_r($weekStat) ,這很好,因為在星期三(關鍵 n°2)該員工工作了 6 小時,其余時間為 0:

Array
(
    [0] => Array
        (
            [sum_count] => 0
        )

    [1] => Array
        (
            [sum_count] => 0
        )

    [2] => Array
        (
            [sum_count] => 6
        )

    [3] => Array
        (
            [sum_count] => 0
        )

    [4] => Array
        (
            [sum_count] => 0
        )

    [5] => Array
        (
            [sum_count] => 0
        )

    [6] => Array
        (
            [sum_count] => 0
        )

)

問題是當我echo($total); & echo((int)$value); 每個$total得到0 ,每個$value只得到1 我需要得到$total = 6

這是我的代碼:

     function getHisStats($vendeur, $theWeek){
        $connexion = connexion();
        $weekStat = array(); // stock les plannings de chaque semaine
 
        $somme = 0;
        $total = 0;

        // On récupere chaque jour de la semaine et on assigne un planning à chaque jour
        for($i = 0; $i < 7; $i++){
            // Creating YY-MM-DD format for fetch in DB
            $dateCurrent = getdate($theWeek[$i]);
            $day = $dateCurrent['mday'];
            $month = $dateCurrent['mon'];
            $year = $dateCurrent['year'];

            // Used to fetch date
            $jour = $year. '-' . $month . '-' . $day;

            // Counting the number of instances of id_planning
            $request_travail = $connexion->prepare("SELECT COUNT(id_planning) AS sum_count FROM plannings WHERE id_employe = ? AND date_planning = ? AND (id_affectation = ? OR id_affectation = ? OR id_affectation = ? OR id_affectation = ?) AND id_validation = ?");
            $request_travail->execute(array($vendeur, $jour, 0, 2, 8, 9, 1));
            $resultat_travail = $request_travail->fetchAll(PDO::FETCH_ASSOC);

            // Stocking the results
            array_push($weekStat, $resultat_travail[0]);
        }
        foreach($weekStat as $key => $value){
            echo($total); // I get 7 at the end because $value is always = 1
            echo((int)$value); // I get 1 everytime
            $total = $total + (int)$value;
        }
        return $weekStat;
    }

記錄單個結果時,您每次都在添加數據行。 由於您使用的唯一值是sum_count ,因此您可以直接添加此值

array_push($weekStat, $resultat_travail[0]['sum_count']);

然后,您應該能夠使用array_sum()而不是循環來計算總數...

$total = array_sum($weekStat);

您也可以改為在 SQL 中進行求和,這可能值得研究。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM