首先讓我試着解釋我正在嘗試做什麼。在不知道密鑰的情況下對多維數組執行if語句
我有一個存儲在數據庫中的事件的日曆,每個事件都是一個工作日。我保存在數據庫中的重要內容是用戶,日期,一年的周(1-52)和工作時間。現在我想通過增加了通過分組在1周,2,3工作時間的工作時間,...,51和52我到目前爲止的代碼來計算工資是:
<?php
include ('require.php');
include ('dblink.php');
$time =[];
$results = mysqli_query($con,"SELECT * FROM events WHERE user = '".$_SESSION['s_username']."'") or die(mysqli_error());
if (mysqli_num_rows($results) > 0){
while($row = mysqli_fetch_assoc($results)){
if($row['week'] % 2 == 0){
$week = $row['week'] - 1; // if its an even week then -1 to make it an odd week to add up the hours of the two weeks together.
}else{
$week = $row['week'];
}
if (isset($time['week']) && $time['week'] == $week){
$time['hours'] += $row['hours']; //If the previous week was added then add the second week to it.
}else{
$year = explode("-", $row['date']);
$time[] = array('week' => $week, 'hours' => $row['hours'], 'year' => $year[0]);
}
}
}
foreach($time as $indTime){
echo $indTime['hours'].' hours were spent on the '.$indTime['week'].' week of '.$indTime['year'] . '<br />';
}
?>
問題出現在第13行,我有一個if
聲明。我知道這是不正確的,因爲我的數組是多維的,並且沒有定義$time['week']
。但我不知道鑰匙,所以我不能這麼做,比如說,$time[23]['week']
。
要嘗試並進一步解釋我的意思,讓我展示一下我的輸出示例。
4.75 hours were spent on the 41 week of 2013
7.5 hours were spent on the 41 week of 2013
4 hours were spent on the 43 week of 2013
7.5 hours were spent on the 43 week of 2013
7.5 hours were spent on the 43 week of 2013
4.5 hours were spent on the 43 week of 2013
6 hours were spent on the 43 week of 2013
4 hours were spent on the 43 week of 2013
7.5 hours were spent on the 43 week of 2013
7 hours were spent on the 45 week of 2013
8 hours were spent on the 45 week of 2013
8 hours were spent on the 45 week of 2013
4.5 hours were spent on the 45 week of 2013
6 hours were spent on the 45 week of 2013
7.5 hours were spent on the 45 week of 2013
5.5 hours were spent on the 45 week of 2013
8 hours were spent on the 45 week of 2013
由於我if
聲明不起作用,它只是創造了在我的數據庫中的每一行一個新的數組。但實際上我希望它做的是每週加起來的小時數是相同的。因此,第41周的所有時間將會加在一起,例如,小時數將是12.25。任何人都知道我能做什麼?
我該如何使用週數作爲關鍵?我對此很新。 – user2989367
@ user2989367:第一個代碼片段,'$ time [$ week] = ...'。但是你應該真的考慮直接把它寫成SQL。 – Jon
哦抱歉沒有看到變化。 – user2989367