动态多维数组会覆盖它自身

时间:2015-03-20 00:48:15

标签: php sql arrays multidimensional-array

编辑: 我现在已经进行了一段时间的实验,看起来它可能是每次调用只能给我一行的SQL,我可以优化它还是以其他方式编写它?


尝试从DB创建/获取动态多维数组/菜单,但它不会打印出DB中的所有行。示例:当打印出两行时,我只使用我现在获得的SQL,当使用嵌套数组时display_children我也只为每个数组获得一行。我尝试用下面的JSON示例解释这个现象。

我已尝试通过该功能发送变量,因此每次调用都会添加自己的变量" level"函数内的每个变量的值,但没有管理它的工作。

这是我的结果示例(使其更具可读性):

[
    {
        "category_id": "1",
        "title": "First test",
        "categories": [
            {
                "category_id": "2",
                "title": "Second category",
                "categories": [
                    {
                        "category_id": "3",
                        "title": "3",
                        "categories": ""
                    }
                ]
            }
        ]
    }
]

这就是我想要/期望的:

[
    {
        "category_id": "1",
        "title": "First test",
        "categories": [
            {
                "category_id": "2",
                "title": "Second category",
                "categories": [
                    {
                        "category_id": "3",
                        "title": "3",
                        "categories": ""
                    }
                ]
            },
            {
                "category_id": "4",
                "title": "Fourth category",
                "categories": ""
            }
        ]
    }
]

数据库表:

table table

以下是代码:

<?php
/* DB info and so on above this line */
function display_children($parent) {

    if(!empty($parent)) {

        global $dbh;
        $query = "SELECT category.*,
                        GROUP_CONCAT(category_hierarchy.category_id SEPARATOR ',') AS subcategories
                    FROM        category 
                    LEFT JOIN   category_hierarchy
                        ON      category_hierarchy.category_parent_id = category.category_id
                    WHERE       category.type = 2 AND ";

        $queryArr   = array();
        $queryArrValue = array();

        $parents = explode(',', $parent);

        foreach($parents as $value) {
            $queryArr[]     = "(category.category_id = ?)";
            $queryArrValue[]    = $value;
        }

        $queryArr = implode(' OR ', $queryArr);

        $query .=   "(".$queryArr.")";
        $query .=   " ORDER BY category.sort_order ASC";

    // Prepare.
        $stmt = $dbh->prepare($query);

    // Execute.
        $stmt->execute($queryArrValue);

    // Fetch results.
        $categories = $stmt->fetchAll();

        $returnArr = array();

                    foreach($categories as $category) {

                        if(!empty($category['subcategories'])) {
                            $parent_arr = array(display_children($category['subcategories']));
                        } else {
                            $parent_arr = '';
                        }

                        $returnArr[] = array(
                            'category_id'   => $category['category_id'],
                            'title'         => $category['title'],
                            'slug'          => $category['slug'],
                            'url'           => $category['url'],
                            'type'          => $category['type'],
                            'sort_order'    => $category['sort_order'],
                            'categories'    => $parent_arr
                            );
                    }

                    return $returnArr;
    }

}

$arr = array();

// Query.

    $query =    "SELECT         category.*,
                                GROUP_CONCAT(category_hierarchy.category_id SEPARATOR ',') AS subcategories     
                FROM            category 
                LEFT JOIN       category_hierarchy
                    ON          category_hierarchy.category_parent_id = category.category_id
                WHERE           category.type = 1
                ORDER BY        category.sort_order ASC
                ";

    // Prepare.
        $stmt = $dbh->prepare($query);

    // Execute.
        $stmt->execute();

    // Fetch results.
        $categories = $stmt->fetchAll();

        $countedRows = count($categories);

        foreach($categories as $category) {
            $parent_arr = '';
            if(!empty($category['subcategories'])) {
                $parent_arr = array(display_children($category['subcategories']));
            } 

            $arr[] = array(
                    'category_id'   => $category['category_id'],
                    'title'         => $category['title'],
                    'slug'          => $category['slug'],
                    'url'           => $category['url'],
                    'type'          => $category['type'],
                    'sort_order'    => $category['sort_order'],
                    'categories'    => $parent_arr
            );
        }

/* Output JSON */
    header('Content-type: application/json');
    echo json_encode($arr);
    die();
?>

1 个答案:

答案 0 :(得分:1)

这是SQL,因为我使用GROUP_CONCAT我必须添加GROUP BY

SELECT      
category.*,
GROUP_CONCAT(category_hierarchy.category_id SEPARATOR ',') AS subcategories 

FROM            category
LEFT JOIN       category_hierarchy    ON        category.category_id = category_hierarchy.category_parent_id
WHERE           category.type = '1'

GROUP BY        category.category_id
ORDER BY        category.sort_order ASC

See description to answer here