【问题标题】:Use array to convert mysql dayofweek integers to weekday names in while loop?在while循环中使用数组将mysql dayofweek整数转换为工作日名称?
【发布时间】:2016-03-06 18:21:52
【问题描述】:

我试图总结一周中不同日子使用的金额。我保存了一个 MySQL 数据库,其中包含我每次使用金钱的时间戳以及当时使用的金额。

总结我在每个工作日使用的钱时,我希望不同的工作日显示他们友好的丹麦名字,而不是周日的零,周一的 1 等等。

我想办法做到这一点是用不同的日期名称创建一个数组,然后用我的数组中的工作日名称替换我的 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 />";
}

任何帮助解决这个问题将不胜感激。

【问题讨论】:

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

标签: php mysql arrays loops


【解决方案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 />";

}

【讨论】:

    【解决方案2】:

    在上面的帮助下,我能够解决这个问题。我使用的确切解决方案是这个。我已经描述了我通过添加 cmets 所做的更改:

    // 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 />";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      相关资源
      最近更新 更多