我正在尝试将数据库中的所有
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);
时,每个 0
都会得到 $total
,而每个 1
只能得到 $value
。我需要得到$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 中进行求和,这可能值得研究。