计算php mysql中的多级营销(树)记录

时间:2012-05-07 06:18:44

标签: php mysql database

用户表

enter image description here

在注册时间内,每个用户都必须放置parent_id,谁在parent_id下注册,所以我为它做了不同的表

赞助者表

enter image description here

之后再制作那样的树

enter image description here

我希望像这样计算记录

enter image description here

所以PLZ指导我如何计算这样的记录,或者我有任何方式可以说这种计数我必须在数据库中更改,提前感谢

3 个答案:

答案 0 :(得分:7)

我在表中有Adjacency模型结构,所以我在parent_id下得到了非常好的解决方案count_id

功能在parent_id

下计算user_id
function display_children($parent, $level) {
    $count = 0;
    $result = mysql_query('SELECT user_id FROM sponsers '.'WHERE parent_id="'.$parent.'"');
    while ($row = mysql_fetch_array($result))
    {
           $var = str_repeat(' ',$level).$row['user_id']."\n";

                   //echo $var  after remove comment check tree

                   // i call function in while loop until count all user_id 

           $count += 1 +$this->display_children($row['user_id'], $level+1);

    }
    return $count; // it will return all user_id count under parent_id
} 

通话功能

display_children(999, 0)

答案 1 :(得分:0)

我猜,你正在搜索http://www.sitepoint.com/hierarchical-data-database-2/

它被称为TREE TRAVERSAL。那么在你的情况下你可以用它来计算。
有关该主题的更多信息,请访问Tree data structure

答案 2 :(得分:0)

对于分层数据存储,您可以看到Nested Set Model。详见http://en.wikipedia.org/wiki/Nested_set_model。 希望它能完全符合你的目的。