如何使用php将动态mysql垂直数据显示为水平

时间:2013-07-27 14:43:41

标签: php mysql

我想使用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  |
----------------------------
你可以帮助我吗?提前谢谢。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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