从数据库自引用表创建嵌套数组,并在Smarty模板的嵌套列表中显示

时间:2019-06-29 23:00:48

标签: php mysql arrays database loops

我从数据库中获取行,并且尝试生成父类别及其子类别的数组(子类别也可以有子类别),以便我可以将该数组数据传递到我的smarty模板视图并可以呈现每个类别和子类别的复选框。

Table Categories:

id |      name         | parent_id
 1 |  Electronics      |   0
 2 |  Mobile           |   1
 3 |  iPhone           |   2
 4 |  Men              |   0
 5 |  Shirt            |   4

我希望结果以这样的方式包含parent_id = 0的那些类别成为父类别,并在其下方显示嵌套的子类别:如下所示

Array ( 
    [0] => Array (
            [id] => 1 
            [name] => Electronics 
            [children] => Array (
               [0] => Array (
                        [id] => 2
                        [name] => Mobile
                        [children] => Array (
                                      [0] => Array (
                                             [id] => 3
                                             [name] => iPhone
                                             )
                                      )
                       )
             )
    [1] => Array (
            [id] => 4 
            [name] => Men 
            [children] => Array (
               [0] => Array (
                        [id] => 5
                        [name] => Shirt
                       )
             )
 )  

这是我到目前为止编写的代码:

$parentCat = Shopware()->Db()->query("SELECT * FROM `categories`");
    $cats = [];
    foreach ($parentCat->fetchAll() as $key => $value) {
        $prevId = $value['parent_id'];
        if ($prevId == 0) {
            $data = [
                'id' => $value['id'],
                'name' => $value['name']
            ];
            array_push($cats, $data);
        } else {
            foreach ($cats as $cat) {
                if($value['parent_id'] == $cat['id']) {
                    $childData = [
                        'id' => $value['id'],
                        'name' => $value['name'],
                    ];
                    array_push($cats,$childData);

                }
            }
        }
    }
    print_r($cats);
    die();

我得到的结果是这样的:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Electronics
    )

[1] => Array
    (
        [id] => 2
        [name] => Mobile
    )

[2] => Array
    (
        [id] => 3
        [name] => iPhone
    )

[3] => Array
    (
        [id] => 4
        [name] => Cars
    )

[4] => Array
    (
        [id] => 5
        [name] => Toyota
    )

)

请帮助。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用递归函数:

function addToArr(&$arr, $data) {
    if ($data["parent_id"] == 0)
        return $arr[] =  ["id" => $data["id"], "name" => $data["name"], "children"=> []];
    foreach($arr as &$e) {
        if ($e["id"] == $data["parent_id"]) { // if found add as child
            $e["children"][] = ["id" => $data["id"], "name" => $data["name"], "children"=> []];
            break;
        }
        addToArr($e["children"], $data); // call recursively 
    }
}

实时示例:3v4l

修改

具有HTML标签:

function getHTMLformat($arr) {
    if (!$arr) return "";
    $str = "<ul>" . PHP_EOL; // starting the list 
    foreach ($arr as $e) {
        $str .= "<li>" . $e["name"] . getHTMLformat($e["children"]) . "</li>" . PHP_EOL;
    }
    return $str . "</ul>" . PHP_EOL; // end list
}

echo getHTMLformat($res);