0
$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';
    }

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

期望的输出

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"
4

2 回答 2

1

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

$lastType = 0;
while($row = $stmt->fetch(PDO::FETCH_BOUND)) {
    if ($lastType != $type) {
        $lastType = $type;
        echo "Type " . $lastType . "<br />";
    }
    echo $id.' '.$type.' '.$total.'<br>';
}
于 2013-09-30T13:34:19.837 回答
1

通过创建一个新数组并重新排列元素:

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';
}
于 2013-09-30T13:31:12.903 回答