2015-12-02 36 views
2

我想總結一週中不同日子使用的金額。每次我使用金錢和當時使用的金錢數量時,我都會保留一個帶有時間戳的MySQL數據庫。使用數組來將mysql dayofweek整數轉換爲while循環中的星期幾名稱?

在總結我在每個工作日使用的錢時,我想讓不同的週末出現在他們友好的丹麥名字上,而不是星期天爲零,星期一爲1,等等。

我想辦法做到這一點是創建一個具有不同日期名稱的數組,然後用我的數組中的weekday名稱替換由我的SQL查詢返回的值。

但是因爲我是一個絕對的初學者,所以我很難找到如何告訴我的PHP腳本替換循環中的MySQL值。

下面是代碼我到目前爲止,我認爲可以做一些非常簡單的方法,我只是不能工作了工作:

// An array with the names of the different days in the week in Danish 
$daynames = array('Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'); 

// My SQL query that fetches the days of the weeks from my timestamps 
$query = "SELECT DAYOFWEEK(timestamp), SUM(money) FROM databasetable"; 
$result = mysqli_query($con,$query) or die(mysql_error()); 

// My loop that prints the sum of money from each day 
while($row = mysqli_fetch_array($result)){ 
echo "". $row['SUM(money)'] ." on day ". $row['DAYOFWEEK(timestamp)'] .""; 
echo "<br />"; 
} 

在搞清楚了這一點任何幫助將是非常讚賞。

+1

'$ daynames [$ row ['DAYOFWEEK(timestamp)']]' –

回答

1

用mysql alias或試試這個代碼: -

$query = "SELECT DAYOFWEEK(timestamp) day, SUM(money) total FROM databasetable"; 
$result = mysqli_query($con,$query) or die(mysql_error()); 
while($row = mysqli_fetch_array($result)){ 

echo $row['total'].' on day '.$daynames[$row['day']]; 
echo "<br />"; 

} 
0

我能解決這個讓上面的好幫手。我使用的確切解決方案是這樣的。我已經描述了我對增加的評論所做的更改:

// An array with the names of the different days in the week in Danish 
// I had to have a blank value before my daynames in order to get the correct days for the corresponding MySQL values: 
$daynames = array('', 'Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'); 

// My SQL query that fetches the days of the weeks from my timestamps 
$query = "SELECT DAYOFWEEK(timestamp), SUM(money) FROM databasetable"; 
$result = mysqli_query($con,$query) or die(mysql_error()); 

// My loop that prints the sum of money from each day 
// Added the part that "uses" the array on the values returned from the database 
while($row = mysqli_fetch_array($result)){ 
echo "". $row['SUM(money)'] ." on day ". $daynames[$row['DAYOFWEEK(timestamp)']] .""; 
echo "<br />"; 
}