类别树的递归 php mysql 查询/函数

发布于 2024-10-27 11:43:47 字数 590 浏览 0 评论 0原文

我建立了 oscommerce,并决定在每个类别中添加“最受欢迎”的产品。我需要查询所有子类别,以便可以查询列表中最受欢迎的产品并显示它。

然而。

我有这个函数,但我似乎无法从中获取类别 id 的数组。这个问题与范围有关吗?

 $children_ids = array(); 

function fetch_children($parent) {     

 $result = tep_db_query('SELECT `categories_id` FROM categories WHERE parent_id = "'.(int)$parent.'"'); 

   while($row = tep_db_fetch_array($result)) {


        $children_ids[] = (int)$row['categories_id'];


        fetch_children($row['categories_id']);
   }   
}

此时,我并没有尝试使用 $children_ids 变量访问数据数组,但这似乎不包含任何内容!?我也尝试过 array_push();

有什么想法吗?

I have an oscommerce set up and have decided to add a "most popular" product in each category. I need to query all child categories so that I can then query for the most popular product in the list and display it.

HOWEVER.

I have this function and I just can't seem to get the array of category id's out of it. Is this issue to do with scope??

 $children_ids = array(); 

function fetch_children($parent) {     

 $result = tep_db_query('SELECT `categories_id` FROM categories WHERE parent_id = "'.(int)$parent.'"'); 

   while($row = tep_db_fetch_array($result)) {


        $children_ids[] = (int)$row['categories_id'];


        fetch_children($row['categories_id']);
   }   
}

At this point I am not trying to access the array of data using the $children_ids variable however this doesn't seem to contain anything!? I've also tried array_push();

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

汐鸠 2024-11-03 11:43:47

您正在尝试从函数内部修改全局变量。您可以从函数体内声明该变量为全局变量(但我强烈建议不要这样做),或者让函数返回children_ids数组,这将是这样的(未经测试):

function fetch_children($parent) {

  $result = tep_db_query('SELECT categories_id FROM categories WHERE parent_id = "'.(int)$parent.'"');
  $list = array();
  while($row = tep_db_fetch_array($result)) {

    $list[] = (int)$row['categories_id'];


    $list = array_merge($list, fetch_children($row['categories_id']));
  }
  return $list;
}

$children_ids = fetch_children($root_node_id);

You are trying to modify a global variable from inside a function. You may declare that variable global from inside the function body (but I would strongly recommend against it) or have the function return the array of children_ids, which would be something like this (not tested):

function fetch_children($parent) {

  $result = tep_db_query('SELECT categories_id FROM categories WHERE parent_id = "'.(int)$parent.'"');
  $list = array();
  while($row = tep_db_fetch_array($result)) {

    $list[] = (int)$row['categories_id'];


    $list = array_merge($list, fetch_children($row['categories_id']));
  }
  return $list;
}

$children_ids = fetch_children($root_node_id);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文