获取类别(多个级别)

时间:2014-05-23 12:38:32

标签: php

我正在创建一个脚本,它将从数据库中加载所有类别。我只是不知道如何以更短的方式做到这一点。 我试图找出一种理论上可以加载无限级别类别的方法。

$stmt1 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row1 = $db->fetch($stmt1))
{
    $stmt2 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row1['Rubrieknummer'] . "'");
    while($row2 = $db->fetch($stmt2))
    {


        $stmt3 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row2['Rubrieknummer'] . "'");
        while($row3 = $db->fetch($stmt3))
        {


            $stmt4 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row3['Rubrieknummer'] . "'");
            while($row4 = $db->fetch($stmt4))
            {
                $row3['CATEGORY3'][] = array(
                    'CATEGORY4_NAME'    => ucfirst(strtolower($row4['Rubrieknaam'])),
                );
            }

            $row2['CATEGORY3'][] = array(
                'CATEGORY3_NAME'    => ucfirst(strtolower($row3['Rubrieknaam'])),
                'CATEGORY4'         => $row2['CATEGORY4'],
            );
        }

        $row1['CATEGORY2'][] = array(
            'CATEGORY2_NAME'    => ucfirst(strtolower($row2['Rubrieknaam'])),
            'CATEGORY3'         => $row2['CATEGORY3'],
        );
    }

    $catagories[] = array(
        'CATEGORY_NAME' => ucfirst(strtolower($row1['Rubrieknaam'])),
        'CATEGORY2'     => $row1['CATEGORY2'],      
    );      
}

我想就如何实现这一点提出一些想法。 (我正在使用一个小模板系统来处理正在制作的数组)

编辑:

感谢IvijanStefanStipić,我能够解决这个问题。 这就是我最终做的事情

$categories = build_category(0);

功能:

function build_category($parent, $row = NULL)
{
    global $db;

    // Initialise array
    $data = array();

    // Basic SQL statement
    $sql = "SELECT * FROM Rubriek";

    // Where condition based on $row
    if(is_null($row))
    {
        $where = " WHERE Hoofdrubriek IS NULL";
    }
    else 
    {
        $where = " WHERE Hoofdrubriek = '" . $row['Rubrieknummer'] . "'";
    }

    // Execute query
    $stmt = $db->query($sql . $where);

    // Next level parent
    $next = $parent + 1;

    // Fetch results
    while($row = $db->fetch($stmt))
    {
        $data[] = array(
            'CATEGORY' . $parent . '_NAME'  => ucfirst(strtolower($row['Rubrieknaam'])),
            'CATEGORY' . $next              => build_category($next, $row),
        );
    }

    // Return data
    return $data;
}

1 个答案:

答案 0 :(得分:0)

您对此解决方案有何看法?

function next_level($val)
{
    global $db;
    $stmt = $db->query("SELECT * FROM Rubriek WHERE Rubrieknummer != '" .$val. "' AND Hoofdrubriek = '" .$val. "'");

    while($row = $db->fetch($stmt))
    {
        echo ucfirst(strtolower($row['Rubrieknaam']));
        echo next_level($row['Rubrieknummer']);
    }
}


$stmt = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row = $db->fetch($stmt))
{
    echo ucfirst(strtolower($row['Rubrieknaam']));
    echo next_level($row['Rubrieknummer']);
}

如果我理解正确,这是具有无限子类别的类别数。