[英]PHP mysql create tree-like hierarchy and their count
I'm still new with PHP & MySQL. 我对PHP和MySQL还是很陌生。 This quetion looks simple, but somehow I can't figure the recursive formulae to create tree-like hierarchy by using foreach and array correctly. 这个问题看起来很简单,但是以某种方式我无法通过正确使用foreach和array来计算递归公式来创建树状层次结构。
This is the table structure 这是表结构
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);
This is sample output that I want: 这是我想要的示例输出:
=================================================
| 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 |
=================================================
my full code (currently) 我的完整代码(当前)
<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>
Something like this should work: 这样的事情应该起作用:
$query = $pdo->query("Your select...");
$arr = [];
while($data = $query->fetch()){
$arr[$data['lecturer']][$data['subject']][] = $data['section'];
}
Afterwards you can foreach over the (3d) array: 之后,您可以遍历(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
}
to count everything recursively you can use: 递归计算所有内容,您可以使用:
function count_recursive($array){
$c = 0;
foreach($array as $value)
if(is_array($value))
$c += count_recursive($value);
else
$c++;
return $c;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.