0

我有这样的邻接列表模式结构,我想计算父级的所有标题,例如 Food = 9, Fruit = 6

在此处输入图像描述

使用该功能计算标题

  function display_children($parent, $level) 
     {

    $result = mysql_query('SELECT title FROM tree '.'WHERE parent="'.$parent.'"');

       while ($row = mysql_fetch_array($result))
        {
           $data=  str_repeat(' ',$level).$row['title']."\n";
           echo $data;
           $this->display_children($row['title'], $level+1);
        }   
  }

调用函数

  display_children('Food',0);

结果

通过回声$数据;我得到了我想要的正确结果,但我想数 9

 Fruit Green Peer Red Cherry Yellow Banana Meat Pork

所以请指导我调用函数时如何计算所有数据

4

2 回答 2

2
function display_children($parent, $level) 
{

   $result = mysql_query('SELECT title FROM tree '.'WHERE parent="'.$parent.'"');

   $count = 0;
   while ($row = mysql_fetch_array($result))
    {
       $data=  str_repeat(' ',$level).$row['title']."\n";
       echo $data;
       $count += 1 + $this->display_children($row['title'], $level+1);
    }  
    return $count; 
}
于 2012-05-10T07:26:36.337 回答
0

您可以使用mysql_num_rows,它将包含您的查询返回的行数。

function display_children($parent, $level) 
{
    $result = mysql_query('SELECT title FROM tree '.'WHERE parent="'.$parent.'"');
    $count = mysql_num_rows($result);

    while ($row = mysql_fetch_array($result))
    {
       $data=  str_repeat(' ',$level).$row['title']."\n";
       echo $data;
       $this->display_children($row['title'], $level+1);
    }   
  }

不过,您的菜单查询量很大,您应该真正研究如下解决方案:http ://www.sitepoint.com/hierarchical-data-database-2/

于 2012-05-10T07:28:00.347 回答