按类型使用 Php 从 MySql 输出数据


Outputting data from MySql with Php by type

$sqlFindPath = "select id, type, children from scores order by type, children desc";
    $stmt = $conn->prepare($sqlFindPath);
    $stmt->execute();
    $stmt->bindColumn('id',$id);
    $stmt->bindColumn('type',$type);
    $stmt->bindColumn('children',$total);
    $hasUnapproved = $stmt->rowCount();
    if($hasUnapproved >= 1) {
        while($row = $stmt->fetch(PDO::FETCH_BOUND)) {
            echo $id.' '.$type.' '.$total.'<br>';
        }
    } else {
        echo 'Nothing found';
    }

您在下面看到的是我使用上述选择的数据。如何按类型使用 php 从 mySql 输出数据?

期望的输出

Ex:
Type 1;
"2"     "1"     "60"
"1"     "1"     "50"
Type 2
"3"     "2"     "10"
"4"     "2"     "5"
"5"     "2"     "1"
Type 3
"6"     "3"     "10"
"7"     "3"     "2"

从表中选择的数据

"id"    "type"  "children"
"2"     "1"     "60"
"1"     "1"     "50"
"3"     "2"     "10"
"4"     "2"     "5"
"5"     "2"     "1"
"6"     "3"     "10"
"7"     "3"     "2"

将最后一个类型保存在变量中,并在更改时回显它。

$lastType = 0;
while($row = $stmt->fetch(PDO::FETCH_BOUND)) {
    if ($lastType != $type) {
        $lastType = $type;
        echo "Type " . $lastType . "<br />";
    }
    echo $id.' '.$type.' '.$total.'<br>';
}

通过创建一个新数组并重新处理元素:

if($hasUnapproved >= 1) {
    $arr = array();
    while($row = $stmt->fetch(PDO::FETCH_BOUND)) {
        $arr[$type][] = array($id => $total);
    }
    foreach ($arr as $type => $val) {
        echo $type . ":<br>";
        foreach ($val as $id => $total) {
            echo $id . " total: " . $total . "<br>";
        }
    }
} else {
    echo 'Nothing found';
}