首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在PHP中构建Json数组

在PHP中构建Json数组
EN

Stack Overflow用户
提问于 2021-06-22 10:32:16
回答 1查看 50关注 0票数 0

我试图在php中构建一个json数组,但是构建一个更复杂的数组。关键是,我正试图创建一个用于盘计算的数据库,数组应该是这样的。

每道菜都有一个名字,一个基本重量,直径和高度。它也有半成品,其中包括单一的产品与其重量。

例如,有一种名为“蛋糕”的成品,其基本重量为750克,高度为8厘米,直径为8厘米。现在这个蛋糕是由3种不同的半成品制成的,这些半成品可以达到750克。

g.)

  • Decorations.
  1. 面团(300克)
  2. 糖霜(300 G)(150 g.)

现在,每一个半产品都有自己的单一产品来构建它。

面团:300克。

  1. 面粉100克
  2. 水100 g
  3. 还有别的100 g。

以此类推,每半个产品。

我尝试过构建数组,但是这个看起来有点困难,对于如何做到这一点有什么建议吗?谢谢!

编辑:我需要这样的东西

代码语言:javascript
运行
复制
[
  {
    "Title": "Cake",
    "base_weight": 750,
    "base_height": 8,
    "base_diameter": 14,
    "half_products": [
      {
        "title": "Dough",
        "weight": 300,
        "ingredients": [
          {
            "title": "Flour",
            "Weight": 150
          },
          {
            "title": "Water",
            "Weight": 150
          }
        ]
      },
      {
        "title": "Icing",
        "weight": 300,
        "ingredients": [
          {
            "title": "Flour",
            "Weight": 150
          },
          {
            "title": "Water",
            "Weight": 150
          }
        ]
      },
      {
        "title": "Decorations",
        "weight": 150,
        "ingredients": [
          {
            "title": "Flowers",
            "Weight": 150
          }
        ]
      }
    ]
  }
]
EN

回答 1

Stack Overflow用户

发布于 2021-06-22 10:50:57

您可以对其使用递归树方法,然后可以轻松地将其转换为json。阿诺德勒布朗在此之前对其进行了编码,https://stackoverflow.com/a/4844073/2528471

代码语言:javascript
运行
复制
function buildTree($items) {
    $childs = array();

    foreach($items as &$item)
        $childs[(int)$item['parent_id']][] = &$item;

    foreach($items as &$item)
        if (isset($childs[$item['id']]))
            $item['childs'] = $childs[$item['id']];

    return $childs[0];
}
$tree = buildTree($items); // $items variable must store all data from your database table

您可以使用它,然后轻松地使用标准的php方法。

代码语言:javascript
运行
复制
json_encode($tree);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68081939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档