PHP mysql创建树状层次结构及其计数

时间:2014-11-07 01:48:09

标签: php mysql count tree

我还是PHP& MySQL的。这个查询看起来很简单,但不知怎的,我无法通过正确使用foreach和数组来计算递归公式来创建树状层次结构。

这是表结构

 CREATE TABLE IF NOT EXISTS `table` (
`id` int(2) NOT NULL,
  `lecturer` varchar(50) NOT NULL,
  `subject` varchar(9) NOT NULL,
  `section` int(2) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `table` (`id`, `lecturer`, `subject`, `section`) VALUES
(1, 'Prof A', 'info2222', 1),
(2, 'Prof A', 'info2222', 2),
(3, 'Prof A', 'info3333', 1),
(4, 'Prof A', 'info3333', 3),
(5, 'Prof B', 'info4444', 1);

这是我想要的示例输出:

=================================================
|  lecturer > subject > section |  count total  |
=================================================
|  Prof A                       |   4           |
|  |---info2222                 |   2           |
|  |    |---1                   |   1           |
|  |    |---2                   |   1           |
|  |                            |               |
|  |---info3333                 |   2           |
|       |---1                   |   1           |
|       |---3                   |   1           |
|                               |               |
|  Prof B                       |   1           |
|   |---info4444                |   1           |
|       |---1                   |   1           |
=================================================

我的完整代码(目前)

<html>  
<head>
<?php

mysql_select_db('testing',mysql_connect('localhost','root',''))or die(mysql_error());

function count_recursive($array)
{
    $c = 0;
    foreach($array as $value)
    {   
        if(is_array($value))
            $c += count_recursive($value);
        else
            $c++;
    return $c;
    }
}

?>

</head>

<body>

<?php

    $query = $pdo->query("Select * from table");
    $arr = [];
    while($data = $query->fetch())
    {
        $arr[$data['lecturer']][$data['subject']][] = $data['section'];
    }

    foreach($arr as $lecturer => $lvalues)
    {
        echo $query['lecturer'] ;
        foreach($lvalues as $subject => $svalues)
        {
           echo $query['subject'] ;
            foreach($svalues as $section)
            {
                echo $query['section'] ;
            }
        }
    }

?>

</body>
</html> 

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

$query = $pdo->query("Your select...");
$arr = [];
while($data = $query->fetch()){
    $arr[$data['lecturer']][$data['subject']][] = $data['section'];
}

之后你可以预告(3d)数组:

foreach($arr as $lecturer => $lvalues){
    //echo your lecturer here
    foreach($lvalues as $subject => $svalues){
        //echo your subject here
        foreach($svalues as $section)
            //echo sour section here
}

以递归方式计算所有内容,您可以使用:

function count_recursive($array){
    $c = 0;
    foreach($array as $value)
        if(is_array($value))
            $c += count_recursive($value);
        else
            $c++;
    return $c;
}