我在尝试解决这个问题时遇到了一些麻烦。我有一个账户图表,我想总结一下钱栏。我的表“类别”有一个自动关系:
category_table
- id
- parent_id
- category
** 我不知道账户图表有多深。它可以有 1,2,3,4,5...多个级别。
这是一个例子:
我想要的是:
Category Name |$
-------------------------------
Category 1 |160.00
Category 1.1 |130.00
some expense | 50.00
some expense | 80.00
Category 1.2 | 30.00
some expense | 10.00
some expense | 20.00
-------------------------------
Category 2 |160.00
Category 2.1 |150.00
some expense |100.00
some expense |150.00
Category 2.1 | 70.00
some expense | 50.00
some expense | 20.00
-------------------------------
我有的:
Category Name |$
-------------------------------
Category 1 | 0.00
Category 1.1 | 0.00
some expense | 50.00
some expense | 80.00
Category 1.2 | 0.00
some expense | 10.00
some expense | 20.00
-------------------------------
Category 2 | 0.00
Category 2.1 | 0.00
some expense |100.00
some expense |150.00
Category 2.1 | 0.00
some expense | 50.00
some expense | 20.00
-------------------------------
我已经在php中尝试过这个递归函数,但它不起作用=/
function display_children($parent) {
$sql = "SELECT c.id, c.category,
(SELECT COUNT(*) FROM category c1 WHERE c1.parent_id = c.id) As Total,
(SELECT SUM(p.value) FROM payables p WHERE p.category_id = c.id) As TotalToPay
FROM category c
WHERE c.parent_id = {$parent}
ORDER BY c.category";
$result = mysql_query($sql);
$ret = "<ul>";
$totalcategory = 0;
while ($row = mysql_fetch_assoc($result)) {
if ($row['Total'] > 0) {
$totalcategory = $totalcategory + (empty($row['TotalToPay']) ? 0 : $row['TotalToPay']);
$ret .= "<li><a href='#" . $row['id'] . "'>" . $row['category'] . " - " . $totalcategory . "</a>";
$ret .= display_children($row['id']);
$ret .= "</li>";
} elseif ($row['Total']==0) {
$totalcategory = ($totalcategory + empty($row['TotalToPay']) ? 0 : $row['TotalToPay']);
$ret .= "<li><a href='" . $row['id'] . "'>" . $row['category'] . " - " . $totalcategory . "</a></li>";
} else;
}
$ret .= "</ul>";
return $ret;
}
echo display_children(0);
它向我展示了:
Category 1 - 0
Category 1.1 - 0
Category 1.2 - 0
expense 1 - 25.90
expense 2 - 0
expense 3 - 3.80
Category 2 - 0
Category 2.1 - 0
Category 2.2 - 0
Category 2.3 - 0
Category 3 - 0
Category 3.1 - 52.00
...任何想法?...谢谢 :)