我在PHP中使用递归函数遇到了一些麻烦 . 我正在创建一个功能,可以在数据库中创建基于类别的链接 . 使用“parent_id”将表创建为无限级别,以检查该类别的父ID .

我还包括一个创建链接的字段“category_link” . 我的问题在于使用递归函数创建链接系统 .

例如我有类别:汽车(ID 1)(链接/汽车) - 沃尔沃(ID 2)(链接/沃尔沃) - 奥迪(ID 3)(链接/奥迪)

因此,如果我构建一个函数来为ID2创建链接,那么最终的链接应该是/ cars / volvo . 我的功能只是检索最后一个,/ volvo而不是/ cars / volvo

function GetSlug($mysqli)
{
    if (isset($_POST)) {
        $cat = validar($mysqli, $_POST['card_category']);
        if ($stmt = $mysqli->prepare("SELECT * FROM categories WHERE id = ? LIMIT 1")) {
            $stmt->bind_param("i", $cat);
            $stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
            ($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
            if ($stmt_result->num_rows > 0) {
                $category = array(
                    'categories' => array(),
                    'parent_cats' => array()
                );
                while ($row_data = $stmt_result->fetch_assoc()) {
                    $parent = $row_data['parent_id'];
                    //creates entry into categories array with current category id ie. $categories['categories'][1]
                    $category['categories'][$row_data['id']] = $row_data;
                    //creates entry into parent_cats array. parent_cats array contains a list of all categories with children
                    $category['parent_cats'][$row_data['parent_id']][] = $row_data['id'];
                }
                echo buildcat($parent, $category);
            } else {
                return false;
            }
        }
    }
}

第二个功能:

function buildcat($parent, $category)
{
    $html = "";
    if (isset($category['parent_cats'][$parent])) {
        foreach ($category['parent_cats'][$parent] as $cat_id) {
            if (!isset($category['parent_cats'][$cat_id])) {
                $html .= $category['categories'][$cat_id]['category_link'] . "
"; } if (isset($category['parent_cats'][$cat_id])) { $html .= $category['categories'][$cat_id]['category_link']; $html .= buildcat($cat_id, $category); } } } return $html; }

我想我的问题是因为我只从DB中获取所选类别ID的信息,而不是获得属于该类别的parent_id的所有类别 . 我对此感到头痛 . 你能帮我么?谢谢!