-2

我想使用 PHP 在 html 表中将动态 mysql 垂直数据显示为水平。我的桌子就像

mysql> select * from role_perm;

-------------------------------------------
| id  | userID  | roleID | permID | value | 
--------------- ---------------------------
| 1   |   2     |   1    |   1    | 1     |
|------------------------------------------
| 2   |   2     |   1    |   2    | 0     |
|------------------------------------------
| 3   |   2     |   1    |   3    | 0     |
|------------------------------------------
| 4   |   2     |   2    |   4    | 0     |
-------------------------------------------
| 5   |   2     |   2    |   1    | 1     |
|------------------------------------------
| 6   |   2     |   2    |   2    | 1     |
|------------------------------------------
| 7   |   2    |   2    |   3    | 0     |
|------------------------------------------
| 8   |   2     |   2    |   4    | 1     |
-------------------------------------------
| 9   |   5     |   1    |   1    | 1     |
|------------------------------------------
| 10  |   5     |   1    |   2    | 0     |
|------------------------------------------
| 11  |   5     |   1    |   3    | 0     |
|------------------------------------------
| 12  |   5     |   1    |   4    | 0     |
-------------------------------------------

等等...

我想在html表格中显示

----------------------------
|  role | permissions      |
----------------------------
|   1   |   1 | 2 | 3 | 4  |
---------------------------- 
|   2   |   1 | 2 | 3 | 4  |
----------------------------
|   3   |   1 | 2 | 3 | 4  |
-----------------------------
|   4   |   1 | 2 | 3 | 4  |
----------------------------

你能帮帮我吗?先感谢您。

4

2 回答 2

0

我想你也可以用一个漂亮的 MySQL 查询来做到这一点(据说这对性能来说会更好),但由于我不擅长 SQL,这里是 PHP 解决方案:

$arrRoles = array();
while ($row = mysql_fetch_assoc($result)) {
   if (!isset($arrRoles[$row['roleID']])) {
       $arrRoles[$row['roleID']] = array();
   }
   $arrRoles[$row['roleID']][$row['permID']] = $row['value'];
}
var_dump($arrRoles);
于 2013-07-27T14:49:44.157 回答
0

尝试这个:

SELECT 
roleID AS role,
GROUP_CONCAT(DISTINCT permID ORDER BY permID ASC SEPARATOR '|') AS permissions 
FROM role_perm 
GROUP BY roleID 
ORDER BY roleID  
于 2013-07-27T14:54:43.600 回答