php - 如何使用 php mysql 获取嵌套的 json 对象

标签 php mysql json

我正在尝试从同一个表中获取父类别和子类别。我正在使用 php Rest api 来实现同样的目的。

这是我的 table 。

id  parent  category
--------------------
1   | 0 |   Fruits
2   | 0 |   Cars
3   | 1 |   Orange
4   | 1 |   Apple
5   | 0 |   Books
6   | 2 |   Benz
7   | 5 |   Comics
8   | 2 |   Honda
9   | 5 |   Fantasy

如何使用 php/mysql 查询获取以下 json。

{
    "categories": [{
            "id": "1",
            "category": "Fruits",
            "subCat": [{
                "id": "3",
                "category": "Orange"
            }, {
                "id": "4",
                "category": "Apple"
            }]
        }, {
            "id": "2",
            "category": "Cars",
            "subCat": [{
                "id": "6",
                "category": "Benz"
            }, {
                "id": "8",
                "category": "Honda"
            }]

        }, {
            "id": "5",
            "category": "Books",
            "subCat": [{
                "id": "7",
                "category": "Comics"
            }, {
                "id": "9",
                "category": "Fantasy"
            }]

        }

    ]
}

感谢您的帮助。

最佳答案

我认为这会解决您的问题

    function buildTree(array $elements, $parentId = 0)  {
    $branch = array();
    foreach($elements as $element)
        {
        if ($element['parent'] == $parentId)
            {
            $children = buildTree($elements, $element['id']);
            if ($children)
                {
                $element['subCat'] = $children;
                }

            $branch[] = $element;
            }
        }

    return $branch;
    }

$query1 = mysql_query("select * from table");

while ($rlt2 = mysql_fetch_array($query1, MYSQL_ASSOC))
    {
    $child[] = $rlt2;
    }

$tree['categories'] = buildTree($child);
$this->response($this->json($tree) , 200);

关于php - 如何使用 php mysql 获取嵌套的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39527670/

相关文章:

java - PHP JSON 到 Java 由于不可见字符而无法解析

php - Zend 框架 : Error Reporting is shut down regardless of ini File

php - 在 mysql 中得到错误的结果?

php - 在php中上传文件时发生错误(图片)

php - 如何将 iPhone 联系人与数据库同步?

javascript - 使用来自 JSON 数据的不同值,而不是使用 Typeahead 的 displayKey

php - yii 中的下拉样式

mysql - Rails 4 ActiveRecord::Base.connection.execute to_json 错误地编码了 DateTime

json - 如何从另一个模式引用 json 模式定义

php - 为什么代码在重定向后执行