我试图在php中构建一个json数组,但是构建一个更复杂的数组。关键是,我正试图创建一个用于盘计算的数据库,数组应该是这样的。
每道菜都有一个名字,一个基本重量,直径和高度。它也有半成品,其中包括单一的产品与其重量。
例如,有一种名为“蛋糕”的成品,其基本重量为750克,高度为8厘米,直径为8厘米。现在这个蛋糕是由3种不同的半成品制成的,这些半成品可以达到750克。
g.)
现在,每一个半产品都有自己的单一产品来构建它。
面团:300克。
以此类推,每半个产品。
我尝试过构建数组,但是这个看起来有点困难,对于如何做到这一点有什么建议吗?谢谢!
编辑:我需要这样的东西
[
{
"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
}
]
}
]
}
]
发布于 2021-06-22 10:50:57
您可以对其使用递归树方法,然后可以轻松地将其转换为json。阿诺德勒布朗在此之前对其进行了编码,https://stackoverflow.com/a/4844073/2528471
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方法。
json_encode($tree);
https://stackoverflow.com/questions/68081939
复制相似问题