PHP / MySQL - 制作一个"树"从表中的值按类别

时间:2014-09-20 12:19:04

标签: php mysql

在MySQL数据库中,我有3列:类别,名称和电话。表看起来像这个例子:

Work       David     777444555
School     Susan     776457333
Work       Peter     743234556
Work       Diana     765432456
Hockey     Ben       786432567
School     Tom       765434566
School     John      765457865
etc...

那么如何做一个"树"使用此表中的PHP结果(从A到Z排序)?我需要这样的例子:

Hockej:
 - Ben, 786432567
 - etc.
School:
 - John, 765457865
 - Susan, 776457333
 - Tom, 765434566
Work:
 - David, 777444555
 - Diana, 765432456
 - Peter, 743234556

2 个答案:

答案 0 :(得分:0)

SELECT category,
       GROUP_CONCAT(CONCAT(Name, ', ', Phone) ORDER BY Name SEPARATOR ';' ) Names
FROM
    yourtable
GROUP BY category

答案 1 :(得分:0)

我写了这段代码,它似乎有效,但请检查一下,如果没有可能造成麻烦的错误: - )

$DBSERVER = 'server';
$DBUSER = 'user';
$DBPASS = 'password';
$DB = 'database';

$login = mysql_connect($DBSERVER, $DBUSER, $DBPASS) or die("Could not connect: " . mysql_error()); 
mysql_select_db($DB, $login) or die ('Can\'t use database : ' . mysql_error()); 
mysql_query("SET NAMES UTF8");



$query = "SELECT * FROM tree ORDER BY category, name"; 
$result = mysql_query($query); 

if(!$result){ 
  echo  mysql_error() . " - " . mysql_errno(); 
} 

else{ 
  $memory = '';
  while ($row = mysql_fetch_assoc($result)){
    if ($row['category'] != $memory){
      $memory = $row['category'];
      echo "<b>".$memory."</b><br>";
    }
    echo " - ".$row['name'].", ".$row['phone']."<br>";
  }
}

这段代码没有错误吗?