PHP mysql create tree-like hierarchy and their count -
i'm still new php & mysql. quetion looks simple, somehow can't figure recursive formulae create tree-like hierarchy using foreach , array correctly.
this table construction
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 `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 sample output want:
================================================= | lecturer > subject > section | count total | ================================================= | prof | 4 | | |---info2222 | 2 | | | |---1 | 1 | | | |---2 | 1 | | | | | | |---info3333 | 2 | | |---1 | 1 | | |---3 | 1 | | | | | prof b | 1 | | |---info4444 | 1 | | |---1 | 1 | =================================================
my total 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 $value) { if(is_array($value)) $c += count_recursive($value); else $c++; homecoming $c; } } ?> </head> <body> <?php $query = $pdo->query("select * table"); $arr = []; while($data = $query->fetch()) { $arr[$data['lecturer']][$data['subject']][] = $data['section']; } foreach($arr $lecturer => $lvalues) { echo $query['lecturer'] ; foreach($lvalues $subject => $svalues) { echo $query['subject'] ; foreach($svalues $section) { echo $query['section'] ; } } } ?> </body> </html>
something should work:
$query = $pdo->query("your select..."); $arr = []; while($data = $query->fetch()){ $arr[$data['lecturer']][$data['subject']][] = $data['section']; }
afterwards can foreach on (3d) array:
foreach($arr $lecturer => $lvalues){ //echo lecturer here foreach($lvalues $subject => $svalues){ //echo subject here foreach($svalues $section) //echo sour section here }
to count recursively can use:
function count_recursive($array){ $c = 0; foreach($array $value) if(is_array($value)) $c += count_recursive($value); else $c++; homecoming $c; }
php mysql count tree
No comments:
Post a Comment