[英]PHP mysql create tree-like hierarchy and their count
我對PHP和MySQL還是很陌生。 這個問題看起來很簡單,但是以某種方式我無法通過正確使用foreach和array來計算遞歸公式來創建樹狀層次結構。
這是表結構
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>
這樣的事情應該起作用:
$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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.