dongqu2863 2014-07-09 19:50
浏览 49
已采纳

无法使用PHP构建嵌套JSON

I am having trouble getting these arrays to nest properly. I am grabbing all the rows from a SQL database and building an array to output in JSON for my crud app. One category has been easy, but the client now wants subcategories and that's when I hit a major wall. I am trying to nest these subcategories into categories. I can do either, but am failing to get them working together. The following is my PHP code:

while ($row = $query->fetch_assoc()) {
    $categories[$row['category']][] = array(
        $row['subcategory'] => $subcategories[$row['subcategory']][] = array(
            'id'                 => $row['id'],
            'item_name'          => $row['item_name'],
            'description'        => $row['description'],
            'price'              => $row['price'],
        ),
    );
}

foreach ($categories as $key => $value) {
    $category_data[] = array(
        'category'   => $key,
        'category_list' => $value,
    );
}

foreach ($subcategories as $key => $value) {
    $subcategory_data[] = array(
        'subcategory'   => $key,
        'subcategory_list' => $value,
    );
}

When I json_encode($category_data) I get the following JSON:

[
{
    "category": "Beer",
    "category_list": [
        {
            "Draft Beer": {
                "id": "1",
                "item_name": "Yuengling",
                "description": "Lager. Pottstown, Pa. An American classic."
            }
        },
        {
            "Draft Beer": {
                "id": "6",
                "item_name": "Bud Light",
                "description": "American Light Lager"
            }
        },
        {
            "Domestic Bottles": {
                "id": "9",
                "item_name": "Stone IPA",
                "description": "India Pale Ale.<em> Escondido, Colo."
            }
        }
    ]
},
{
    "category": "Wine",
    "category_list": [...]
}
]

Which might work, but I would like it to join the like keys (ie: Draft Beer) into the same array. It does do that when I json_encode($subcategory_data) as shown below, but its not separated into categories, just the subcategories.

[
{
    "subcategory": "Draft Beer",
    "subcategory_list": [
        {
            "id": "1",
            "item_name": "Yuengling",
            "description": "Lager. Pottstown, Pa."
        },
        {
            "id": "6",
            "item_name": "Bud Light",
            "description": "American Light Lager. Milwaukee, Wisc."
        }
    ]
},
{
    "subcategory": "Red Wine",
    "subcategory_list": [
        {
            "id": "17",
            "item_name": "Kendall-Jackson",
            "description": "Cabernet Sauvignon, 2010."
        },
        {
            "id": "18",
            "item_name": "Sanford",
            "description": "Pinot Noir, 2011. Lompoc, Calif"
        }
    ]
},
{
    "subcategory": "Domestic Bottles",
    "subcategory_list": [
        {
            "id": "9",
            "item_name": "Stone IPA",
            "description": "India Pale Ale. Escondido, Colo."
        },
        {
            "id": "10",
            "item_name": "Blue Moon",
            "description": "Belgian-style Wheat Ale."
        }
    ]
}
]

So my question is why does it merge in the second set of data but not the first. How do I get the subcategory_data into the category_data. Any help id truly appreciated. Below is an example if what I am looking for:

{
    "category_name":"Beer",
    "category_list" : [
        {
            "subcategory_name": "Draft Beer",
            "subcategory_list": [
            {
                "id": "1",
                "item_name": "Yuengling",
                "description": "Lager. Pottstown, Pa."
            },
            {
                "id": "6",
                "item_name": "Bud Light",
                "description": "American Light Lager. Milwaukee, Wisc."
            }
        }
    ]   
},
{
    "category_name":"Wine",
    "category_list" : [
        {
            "subcategory_name": "Red Wine",
            "subcategory_list": [...]
        }
    ]
}

Thanks for looking, I am fairly new to PHP and am relying on my javascript skills.

  • 写回答

1条回答 默认 最新

  • dsour68888 2014-07-09 20:46
    关注

    First, try var_dump($categories). You'll see that you're building a rather weird data structure (you have arrays of 1-element arrays...). The following code will build a simpler structure:

    $categories[$row['category']][$row['subcategory']][] = array(
      'id'                 => $row['id'],
      'item_name'          => $row['item_name'],
      'description'        => $row['description'],
      'price'              => $row['price'],
      );
    

    This will serialize to JSON that's probably acceptable as is:

    {
      "Beer": {
        "Draft Beer": [
          {
            "id": "1",
            "item_name": "Yuengling",
            "description": "Lager. Pottstown, Pa."
          },
          {
            "id": "6",
            "item_name": "Bud Light",
            "description": "American Light Lager. Milwaukee, Wisc."
          }
        ],
        ...
    

    An additional transformation gets the data in the format you asked for:

    foreach ($categories as $category_name => $subcategories) {
      $subcategory_data = array();
      foreach ($subcategories as $subcategory_name => $items) {
        $subcategory_data[] = array(
          'subcategory_name' => $subcategory_name,
          'subcategory_list' => $items
          );
      }
      $category_data[] = array(
        'category_name' => $category_name,
        'category_items' => $subcategory_data
        );                 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算