简体   繁体   English

如何将MySQL中具有相同值的行分组为PHP?

[英]How to group rows with the same value from mySQL into php?

So im trying to sort the different rows per day and just output some "testdate" info of the different unique rows, but the problem i have is that only the first id get the correct outputted "testdate" not all the others. 因此,我试图每天对不同的行进行排序,并仅输出不同唯一行的一些“ testdate”信息,但是我遇到的问题是,只有第一个id才能获得正确的输出“ testdate”,而不是其他所有ID。 Please look at my example of what i have now and what i'm looking for. 请看一下我现在所拥有和正在寻找的示例。

This is my table with the name "1702": 这是我的名称为“ 1702”的表:

╔════╦══════════╦═════════════════════╗
║ id ║ testdate ║     datecreated     ║
╠════╬══════════╬═════════════════════╣
║ 1  ║   1702   ║ 2019-02-16 14:48:28 ║
║ 2  ║   1702   ║ 2019-02-17 14:48:58 ║
║ 8  ║   1802   ║ 2019-02-16 14:50:07 ║
║ 4  ║   1702   ║ 2019-02-17 14:48:51 ║
║ 7  ║   1802   ║ 2019-02-17 14:50:34 ║
║ 6  ║   1702   ║ 2019-02-17 14:48:54 ║
║ 9  ║   1802   ║ 2019-02-16 14:50:09 ║
║ 10 ║   1802   ║ 2019-02-17 14:50:12 ║
║ 11 ║   1602   ║ 2019-02-14 14:50:55 ║
║ 12 ║   1602   ║ 2019-02-14 14:51:11 ║
╚════╩══════════╩═════════════════════╝

My current result is this: 我当前的结果是这样的:

2019-02-17
2,4,7,6,10 1702

2019-02-16
1,8,9 1702

2019-02-14
11,12 1602

But i want it to be like this: 但我希望它是这样的:

2019-02-17
2 1702
4 1702
7 1802
6 1702
10 1802

2019-02-16
1 1702
8 1802
9 1802

2019-02-14
11 1602
12 1602

This is the code i have: 这是我的代码:

$sql = 'SELECT  DATE(datecreated), GROUP_CONCAT(id) as grouped_name, testdate FROM `1702` GROUP BY DATE(datecreated) DESC';
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['DATE(datecreated)'].'<br>';
    echo '
        <div class="box-bettype">
            <p class="box-bettype-text">'. $row['grouped_name']. ' ' . $row ['testdate'] . '</p>
        </div>
        ';
}

Try this: 尝试这个:

$sql = 'SELECT DATE(datecreated) as datecreated, id as grouped_name, testdate FROM `1702` ORDER BY DATE(datecreated) DESC';
$result = mysqli_query($conn,$sql);
$prevDate = null;
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['datecreated'] !== $prevDate ? $row['datecreated'].'<br>' : '';
    $prevDate = $row['datecreated'];
    echo '
        <div class="box-bettype">
            <p class="box-bettype-text">'. $row['grouped_name']. ' ' . $row ['testdate'] . '</p>
        </div>
        ';
}

I removed GROUP_CONCAT and just comparing current date with previous date. 我删除了GROUP_CONCAT,仅将当前日期与之前的日期进行了比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM