PHP 递归函数/循环确定菜单、项目等的最低级别
我在编写一个简单(!)PHP 函数以在以下情况下返回值数组时遇到问题。
我有一个数据库表,它在两个字段“parent_id”和“category_id”中简单列出了父类别和子类别(例如菜单、子菜单、子子菜单)。我想通过表格向下挖掘以拉出所有底部的category_id - 即那些没有被列为任何其他人的“父母”,而是输入到
我的 函数的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 数组中,因为我需要一些东西去 XXXXXXXXXXXXXX 所在的地方,但这极大地回避了我,
我假设我需要以某种方式标记函数的每个循环。但我不明白如何 - 谢谢 - 格雷姆
I am having trouble with writing a simple(!) PHP function to return an array of values under the following scenario.
I have a database table that simply lists parent and child categories (e.g. menu, sub menu, sub sub menu) in two fields 'parent_id' and 'category_id'. I want to tunnel down through the table to pull out all the bottom category_ids - i.e. those that are not listed as 'parents' to any others but are children (or grand children or great grand children) of the category_id input to the function
I have a function a bit like this (it runs on osCommerce based code so the sql query stuff looks odd
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
If I input a value to the function that has children then it will produce those in an array of $bottom_categories and then do the same all the way down to the final bottom categories - however these are not singled out and placed in the $results array as I need something to go where XXXXXXXXXXXXXX is but that is evading me mightily.
I'm assuming that I need to label each loop of the function in some way but I fail to see how - thanks - Graeme
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以纯粹使用 SQL 来完成此操作:
You can do this purely in SQL:
我总是会运行 else 情况并检查查询是否有任何结果。如果它没有子项,则您已准备好并将其插入列表中;其他方面与以前相同。
示例代码:
I would always run the else case and check if the query has any results. If it has no children you are ready and insert it into the list; otherwise same as before.
Example code: