从数据库获取嵌套JSON的最佳方法是什么?

时间:2016-07-04 06:20:43

标签: javascript php mysql sql api

例如,我有两个表:

PRODUCTS (id, category_id, name);
CATEGORIES (id, name);

我希望传递给前端JSON,如:

"categoryProjects": [
    {
        "id" : 1,
        "name" : "some category name",
        "projects": [
            {
                "id": 1,
                "name": "Product1"
            },
            {
                "id": 2,
                "name": "Product2"
            },
        [   
    },
    {
        "id" : 2,
        "name" : "second category name",
        "projects": [
            {
                "id": 3,
                "name": "Product3"
            }
        [   
    }
]

我的问题是:最好的方法是什么?我希望它尽可能高效。我在php,数据库(mysql)中有简单的服务器,我想要创建API。我想知道为我的前端做端点的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

你需要做一个SQL连接,就像这样

<?php
$sth = $pdo->query("select products.*, categories.name as category from products left join categories on products.category_id = categories.id");
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);

$categories = [];

foreach ($rows as $row)
{
    if (!isset($categories[$row['category_id']]))
    {
        $categories[$row['category_id']] = [
            "name" => $row['category'],
            "id" => $row['category_id'],
            "products" => []
        ];
    }

    $categories[$row['category_id']]['products'][] = [
        "id" => $row['id'],
        'name' => $row['name']
    ];
}

print json_encode($categories, JSON_PRETTY_PRINT);

然后将返回的表映射到PHP数组并将其转换为JSON。

{ 
  "_id" : ObjectId("577686c89aff4e2e986923c1"),
  "RowSpan" : [
      {
          "PathID" : 1,,
          "Rows" : [108, 206, 399],
      }],
  "Name" : "BICT_1_2_1" 
}

假设您的表是按照您的描述构建的,那么这段代码就会运行。