在此表上使用
[ POSTS ]
| id | title | class |
|----|----------|-------|
| 1 | 4567 | 2 |
| 2 | 1234 | 1 |
| 3 | 9124 | 1 |
| 3 | 9124 | 3 |
________________________
此代码
$statment= $conn->prepare("SELECT * FROM Posts WHERE id = :id AND class in (1,2,3) ORDER BY class ASC");
$statment->execute([':id' => $id]);
$classes = array();
while($row = $statment->fetch()){
if(!isset($classes[$row['class']])){ $classes[$row['class']] = array(); }
$classes[$row['class']][] = $row['title'];
}
foreach($classes as $key => $class){
echo "Class Value: ".$key;
foreach($class as $title){ echo "<a>".$title."</a>"; }
}
当我输入foreach
代码时,每个值都会获得$ key,但echo "Class Value: ".$key;
应该出现一次,然后显示$key
的所有值,但是相反,$ key乘以&amp;当具有例如class = 1的类超过3时,Everything开始中断。
原来是
$key:
ROW VALUE 1
ROW VALUE 1
ROW VALUE 1
会发生什么
$key:
ROW VALUE 1 [id = 1]
$key:
ROW VALUE 1 [id = 2]
$key:
ROW VALUE 1 [id = 3]
当有超过3行且值为1
时$key:
ROW VALUE 1 [id = 1]
$key:
ROW VALUE 1 [id = 1]
$key:
ROW VALUE 1 [id = 2]
$key:
ROW VALUE 1 [id = 3]
此代码是我在此处提出的上一个问题的答案 https://stackoverflow.com/a/43054136/7490349