单独我的Mysql组结果

时间:2012-04-11 01:26:01

标签: php mysql

好吧我有一个来自我的mysql数据库的结果列表,基本上它列出了我查看的网站页面并按日期分组。现在结果很好,一切都很好地分组。并在页面上显示如下。

29/03/2012 09:18页面名称

29/03/2012 09:24页面名称

现在我想做的是看看我是否可以更改格式,以便结果列出如下

29/03/2012

页面名称

页面名称

30/03/2012

页面名称

页面名称

我遇到的一个问题是日期字段是日期时间,虽然我可以从变量中删除日期并使用日期,但我不知道如何列出上面列出的结果。以下是我目前的代码,

$query = "SELECT date, page_name FROM page_views GROUP BY date"; 
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo $row['date']. " - $". $row['page_name'];
echo "<br />";

1 个答案:

答案 0 :(得分:1)

您可以使用PHP中的date()格式化日期时间:

while($row = mysql_fetch_array($result)) { 
    echo date("d/m/Y", strtotime($row['date']));
    echo "<br />";
    echo $row['page_name'];
    echo "<br />"; 
}

这将导致:

29/03/2012

页面名称

30/03/2012

页面名称

编辑:

这是我现在唯一的解决方案:

//First you select only the DISTINCT DATEs without TIME
$query1 = 'SELECT DISTINCT DATE_FORMAT(date, %d/%m/%Y") as date FROM page_views';
$result1 = mysql_query($query1) or die(mysql_error()); 

//Create a while-loop to store DATE data in array
while($row1 = mysql_fetch_array($result1)) {
    $array[]['date'] = $row1['date']

    //SELECT the page_names where the date is LIKE the date in array
    $query2 = 'SELECT page_name FROM page_views WHERE date LIKE "%'.$row1['date'].'%"';
    $result2 = mysql_query($query2) or die(mysql_error());


    //Create a second while-loop to store the pagenames data in array who fits to the date
    while($row2 = mysql_fetch_array($result2) {
        $array[]['pagenames'][] = $row2['page_name'];
    }
}

print_r($array);
//This will output this:
$array = Array(
    [0] => Array(
        [date] => 29/03/2012
        [pagenames] => Array(
            [0] => pagename1
            [1] => pagename2
        )
    )
    [1] => Array(
        [date] => 30/03/2012
        [pagenames] => Array(
            [0] => pagename1
            [1] => pagename2
        )
    )
)

//use foreach to display the data
foreach($array as $entry) {
    echo $entry['date'];
    echo '<br />';
    foreach($entry['pagenames'] as $pagename) {
        echo $pagename;
        echo '<br />';
    }
}