Hi friends,
I have a database named 'abv' with a table named: category -
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| category_id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| number | int(11) | NO | | NULL | |
| parent | int(11) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
+-------------+----------+--------+--------+
| category_id | name | number | parent |
+-------------+----------+--------+--------+
| 1 | Europe | 0 | NULL |
| 2 | BG | 8 | 1 |
| 3 | Sofia | 5 | 2 |
| 4 | Varna | 2 | 2 |
| 5 | Mladost | 4 | 3 |
| 6 | Chaika | 9 | 4 |
+-------------+----------+--------+--------+
I used Barand's code to display its hierarchy:
<?php
//connect to database
$link = mysql_connect('localhost','root','');
mysql_select_db('abv');
$sql = "SELECT category_id, name, parent, number
FROM category";
$res = mysql_query($sql);
while (list($id, $name, $parent, $number) = mysql_fetch_row($res)) {
$data[$parent][] = array('id'=>$id, 'name'=>$name, 'number'=>$number);
}
// function to print a category then its child categories
function displayHierarchy(&$arr, $parent, $indent=0)
{
$ind = $indent * 30;
if (isset($arr[$parent]))
foreach($arr[$parent] as $rec)
{
echo "<div style='width:300px; margin-top:5px; margin-left: {$ind}px; padding:5px; border:1px solid gray;'>
{$rec['name']} - {$rec['number']}
</div>" ;
displayHierarchy($arr, $rec['id'], $indent+1);
}
}
// call the recursive function
displayHierarchy($data, null);
Results:
Europe - 0
BG - 8
Sofia - 5
Mladost - 4
Varna -2
Chaika - 9
My question is, how to get this data displaying a result like this:
Europe - 26
BG - 26
Sofia - 9
Mladost - 4
Varna - 11
Chaika - 9
Thanks in advance