【问题标题】:PHP: Insert database value into different php arrayPHP:将数据库值插入不同的php数组
【发布时间】:2014-08-24 09:38:41
【问题描述】:

我的页面“From”和“To”中有 2 个日期选择器。用户将为每个值选择日期:

FromDate: 01/JUL/2012     ToDate: 31/OCT/2014

这是我的查询:

  $query = mssql_query("SELECT count(startdate) as start
                        FROM user 
                        WHERE startdate between '01 JUL 2012' and '31 OCT 2014' 
                        GROUP BY  month(startdate), year(startdate) 
                        ORDER BY  month(startdate) ASC, year(startdate) ASC");

我想计算从用户选择日期开始的所有记录,按年和月分组并将其存储在 php 数组中。

示例结果:

          JUL AUG SEP OCT NOV DEC

Array2012 = ("52","45","25","62","11","41")

          JAN  FEB  MAR   DEC

Array2013 = ("52","45","25",......,"35")

         JAN  FEB  MAR   OCT

Array2014 = ("52","45","25",.......,"47")

如何循环数据库中的值以便获得这些结果?

【问题讨论】:

    标签: php sql arrays


    【解决方案1】:

    你需要改变几件事:

    • 在您的选择字段中添加年份并使用它将您的结果插入到数组中
    • 更改顺序:先按年排序,然后按月排序

    结果,代码将如下所示:

    $values = array();
    $lastYear = 0;
    
    $query = mssql_query("SELECT count(startdate) as start, 
                        year(startdate) AS year
                        FROM user 
                        WHERE startdate between '01 JUL 2012' and '31 OCT 2014' 
                        GROUP BY  month(startdate), year(startdate) 
                        ORDER BY  year(startdate) ASC, month(startdate) ASC");
    
    while ($data = mssql_fetch_array($query)) {
        if ($data['year'] != $lastYear) {
            $lastYear = $data['year'];
            $values[$data['year']] = array();
        }
        array_push($values[$data['year']], $data['start']);
    }
    
    print_r($values);
    

    $values 将包含:

    Array(
    [2012] => Array("52","45","25","62","11","41"}),
    [2013] => Array("52","45","25",......,"35"),
    [2014] => Array("52","45","25",.......,"47")
    )
    

    【讨论】:

    • 回复得很快..谢谢..我会稍后再试并告诉你结果..非常感谢。
    • 如何打印结果..我试过你说的,但没有结果,页面是空白的..
    • 你可以使用 print_r($values);显示数组中存储的内容
    • 它打印空白.. 哦,我现在明白了,在 array_push 中,它应该是 $data['start'].. 谢谢..
    【解决方案2】:

    尝试使用类似这样的代码 sn-p 来遍历 db 查询的返回值:

    $query = mssql_query("SELECT count(startdate) as start
                        FROM user 
                        WHERE startdate between '01 JUL 2012' and '31 OCT 2014' 
                        GROUP BY  month(startdate), year(startdate) 
                        ORDER BY  month(startdate) ASC, year(startdate) ASC");
        if($query == FALSE){
            die(mysql_error());
        }
        while($row = mysql_fetch_array($query)){
            echo $row['startdate']
        }
    

    希望我对您的理解正确并能提供帮助。

    和平

    【讨论】:

    • 感谢您的回复。我尝试了这种循环,它对我有用,但我不知道如何将值存储在不同的数组中。
    猜你喜欢
    • 2016-05-26
    • 2019-03-09
    • 2015-10-30
    • 1970-01-01
    • 2014-12-30
    • 2017-10-03
    • 2023-03-05
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多