【问题标题】:Find all middle categories from nth child to top level in PHP recursion在 PHP 递归中查找从第 n 个子级到顶层的所有中间类别
【发布时间】:2016-03-05 00:38:37
【问题描述】:

我有分类表:

Category table:
cat_id      cat_pid     cat_name
    1           0       Women's Fashion
    2           1       Women Accessories
    3           2       Wallets & Cardholders
    4           3       Cases

我有父级类别 ID,即“女装 (cat_id = 1)”和叶级类别 ID,即“案例 (cat_id = 4)”

我想查找 4 到 1 之间的所有类别。

这样的数组:

Array(
     [0]=>2
     [1]=>3
)

【问题讨论】:

标签: php mysql recursion categories recursive-query


【解决方案1】:

我不知道你用的是mysqli还是PDO所以我写了基础代码...

<?php

$cats = [];

function find_parent($parent_id){
    global $cats;
    if ($parent_id > 0){
        $q = mysql_query('SELECT cat_pid FROM Category WHERE cat_id = ' . $parent_id);
        $r = mysql_result($q, 0, 'cat_pid');
        if ($r > 0){
            $cats[] = $parent_id;
            find_parent($r);
        }

    }
}

find_parent(4);
array_shift($cats); //it adds first record too and i think you don't want so removing it here...
print_r($cats);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多