PHP递归函数/循环,用于确定菜单,项目等的最低级别

时间:2011-10-08 15:49:48

标签: php loops

我在编写一个简单的(!)PHP函数时遇到问题,在以下场景下返回一个值数组。

我有一个数据库表,它只是在两个字段'parent_id'和'category_id'中列出父类和子类(例如菜单,子菜单,子子菜单)。我想通过表格挖出所有底部的category_ids - 即那些未被列为“父母”的其他人,但是对于函数的category_id输入的孩子(或大孩子或大孩子)

我有一个像这样的函数(它运行在基于osCommerce的代码上,所以sql查询的东西看起来很奇怪

function tep_get_bottom_categories( $categories_id) {
    $bottom_categories_query = tep_db_query("select categories_id from categories where parent_id = '" . $categories_id . "'");
    while ($bottom_categories = tep_db_fetch_array($bottom_categories_query)) {
        if(XXXXXXXXXXXXX)//<---- tried lots of stuff here
            {$results[]=$bottom_categories['categories_id'];}
        else
            {tep_get_bottom_categories( $bottom_categories['categories_id']);
        }
    }//end while loop 
}// end function

如果我为具有子项的函数输入一个值,那么它将生成$ bottom_categories数组中的值,然后一直执行到最终的底部类别 - 但是这些不会被挑选出来放在$ results array因为我需要去XXXXXXXXXXXXXX的地方,但这很大程度上躲避了我。

我假设我需要以某种方式标记函数的每个循环,但我没看到 - 谢谢 - Graeme

2 个答案:

答案 0 :(得分:1)

您可以在SQL中完全执行此操作:

SELECT category_id, (SELECT count(*) 
                     FROM categories AS ci 
                     WHERE ci.parent_id=co.category_id) AS children 
FROM categories AS co 
WHERE parent_id=xxxxx
HAVING children=0

答案 1 :(得分:0)

我总是运行else案例并检查查询是否有任何结果。如果它没有孩子,你就准备好并将其插入列表中;与以前一样。

示例代码:

function tep_get_bottom_categories( $categories_id) {
  $bottom_categories_query = tep_db_query("select categories_id from categories where parent_id = '" . $categories_id . "'");

  if( /* check num_rows == 0 */ {
    {$results[]=$categories_id;}
  } else {
    while ($bottom_categories = tep_db_fetch_array($bottom_categories_query)) {
      {tep_get_bottom_categories( $bottom_categories['categories_id']);}
    }//end while loop 
  }
}// end function