gpt4 book ai didi

PHP(或 jQuery,如果需要): Output related MySQL records from other tables as JSON?

转载 作者:行者123 更新时间:2023-11-29 08:36:47 25 4
gpt4 key购买 nike

我有两个表:

表 1:

Make       Model 1 ID      Model 2 ID      Model 3 ID
---- ---------- ---------- ----------
Ford 1 4 7
Chevrolet 2 3 5
Dodge 6 8 9

表 2:

ID         Model            Engine
---- ----- ------
1 F-150 Triton V8
2 Silverado Vortec V8
3 Corvette LS9 V8
4 Fusion Duratec I4
5 Camaro LSA V8
6 Ram Hemi V8
7 Mustang Modular V8
8 Grand Caravan Pentastar V6
9 Challenger Hemi V8

我希望使用 PHP 将链接数据输出为 JSON(是你所说的吗?我对编程术语有点菜鸟。抱歉。)如果我的 JSON 语法错误,则类似):

 {
[
{
"make": "Ford",
"models":
[
{
"ID": "1",
"info":
{
"model": "F-150",
"engine": "Triton V8",
}
},
{
"ID": "4",
"info":
{
"model": "Fusion",
"engine": "Duratec I4",
}
},
{
"ID": "7",
"info":
{
"model": "Mustang",
"engine": "Triton V8",
}
},
]
},
{
"make": "Chevrolet",
"models":
[
{
"ID": "2",
"info":
{
"model": "Silverado",
"engine": "Vortec V8",
}
},
{
"ID": "3",
"info":
{
"model": "Corvette",
"engine": "LS9 V8",
}
},
{
"ID": "5",
"info":
{
"model": "Camaro",
"engine": "",
}
},
]
}, {
"make": "Dodge",
"models":
[
{
"ID": "6",
"info":
{
"model": "Ram",
"engine": "Hemi V8",
}
},
{
"ID": "8",
"info":
{
"model": "Grand Caravan",
"engine": "Pentastar V6",
}
},
{
"ID": "9",
"info":
{
"model": "Challenger",
"engine": "Hemi V8",
}
},
]
}
]
}

问题是,如何使用 PHP 来做到这一点?感谢您花时间阅读这篇相当长的文章,并提前感谢您尝试提出解决方案。

如果您想建议使用 jQuery 的解决方案,也可以。

最佳答案

您的数据库错误。试试这个结构:

MakeID Make
------ ----
1 Ford
2 Chevrolet
3 Dodge

ModelID MakeID Model Engine
------- ------ -------------- ------
1 1 F-150 Triton V8
2 2 Silverado Vortec V8
3 2 Corvette LS9 V8
4 1 Fusion Duratec I4
5 2 Camaro LSA V8
6 3 Ram Hemi V8
7 1 Mustang Modular V8
8 3 Grand Caravan Pentastar V6
9 3 Challenger Hemi V8

现在你可以做这样的事情:

$sql = mysql_query("select * from `table1` join `table2` using (`MakeID`)");
$out = Array();
while($car = mysql_fetch_assoc($sql)) {
if( !isset($out[$car['MakeID']])) {
$out[$car['MakeID']] = Array("make"=>$car['Make'],"models"=>Array());
}
$out[$car['MakeID']]['models'][] = Array(
"ID"=>$car['ModelID'],
"info":Array(
"model"=>$car['Model'],
"engine"=>$car['Engine']
)
);
}
$out = array_values($out);
echo json_encode($out);

关于PHP(或 jQuery,如果需要): Output related MySQL records from other tables as JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com