我有不同用户及其偏好的表格,如此
+--------+----------+--------------+
| id | user_id | preference_id|
+--------+----------+--------------+
| 15145 | 12 | 1 |
| 15146 | 13 | 1 |
| 15148 | 15 | 2 |
| 15150 | 25 | 2 |
| 15314 | 26 | 3 |
| 15315 | 29 | 1 |
| 15316 | 30 | 3 |
| 15317 | 32 | 3 |
| 15318 | 33 | 1 |
| 15319 | 34 | 2 |
+--------+----------+--------------+
我需要根据偏好设置ID对此用户进行分组。像这样:
+--------+----------+--------------+
| id | user_id | preference_id|
+--------+----------+--------------+
| 15145 | 12 | 1 |
| 15146 | 13 | 1 |
| 15315 | 29 | 1 |
| 15318 | 33 | 1 |
+--------+----------+--------------+
+--------+----------+--------------+
| id | user_id | preference_id|
+--------+----------+--------------+
| 15314 | 26 | 3 |
| 15316 | 30 | 3 |
| 15317 | 32 | 3 |
+--------+----------+--------------+
+--------+----------+--------------+
| id | user_id | preference_id|
+--------+----------+--------------+
| 15148 | 15 | 2 |
| 15150 | 25 | 2 |
| 15319 | 34 | 2 |
+--------+----------+--------------+
我检查了这个mysqli查询,但这显示不能满足我的需求。
$sql="SELECT * FROM gic_user_preference GROUP BY preference_id";
$result=mysqli_query($createCon->connect(), $sql);
while ($arr = mysqli_fetch_assoc($result)) {
var_dump($arr);
}
答案 0 :(得分:1)
似乎你需要通过
订购SELECT * FROM gic_user_preference ORDER BY preference_id
并检查循环中的preference_id更改...否则您必须为每个不同的preference_id执行select并显示结果
答案 1 :(得分:0)
您可以使用由您的组字段索引的关联数组从数据库中获取数据时将数据保存在PHP中:
$groupedData = [];
while ($arr = mysqli_fetch_assoc($result)) {
$groupedData[$arr['preference_id']][] = $arr;
}
然后 $groupedData
将会是
[
1 => [
['id' => 15145,'user_id' => 12, 'preference_id' => 1],
['id' => 15146,'user_id' => 13, 'preference_id' => 1],
//...
],
2 => [
['id' => 15148, 'user_id' => 15, 'preference_id' => 2],
['id' => 15150, 'user_id' => 25, 'preference_id' => 2],
//...
],
3 => [
// ...
],
// ...
]