【问题标题】:Dynamic multidimensional array overrides it self动态多维数组自行覆盖
【发布时间】:2015-03-20 00:48:14
【问题描述】:

编辑: 我已经试验了一段时间,似乎它可能是每次调用只给我一行的 SQL,我可以优化它还是用另一种方式编写它?


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

我试图通过函数发送一个变量,所以每次调用都会将它自己的“级别”值添加到函数内的每个变量中,但没有成功。

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

[
    {
        "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": ""
            }
        ]
    }
]

数据库表:

代码如下:

<?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();
?>

【问题讨论】:

  • 这样更具可读性?试试JSONLint
  • 谢谢,现在它更具可读性...我还添加了有关我的问题的更多信息。
  • 我不确定我是否遵循您的问题,但有可能在function display_children 末尾的foreach 循环中@您return array( ...。这将返回第一个循环(第一个 db 行/子项)并切出函数,即使有更多行。
  • 谢谢,现在我使用一个多维数组来代替返回。不过,我试图描述的第一个问题仍然困扰着我。当我尝试制作一个简单的数组时,比如说 tre 行,它只返回第一个。但是当使用display_children 时,我只为嵌套在另一个数组中的每个数组得到一行,这就是我试图用我的 JSON 示例展示的内容。就像某些东西被覆盖并且不会被打印出来。

标签: php sql arrays multidimensional-array


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 2016-11-28
    • 1970-01-01
    • 2022-11-17
    • 2020-02-20
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多