2 回答
TA贡献2011条经验 获得超2个赞
再次阅读文章后,我意识到,有是在那里尝试已经(对不起,我先前的评论说,否则......)。关于如何解决数据重组问题,我的建议如下:
$newarr=array();
for($i = 0; $i < count($array); $i++){
$obj = json_decode($array[$i]);
$newarr[$obj->GROUP][$obj->BREED][]=$obj->NAME;
}
foreach ($newarr as $group => $breeds) {
echo "<h1>$group</h1>\n";
foreach ($breeds as $breed => $vehicles)
echo "<p><b>$breed</b><br>\n".join("<br>\n",$vehicles)."</p>\n";
}
您可以在此处找到工作演示:https : //rextester.com/OYD48391
TA贡献1818条经验 获得超3个赞
您需要先重构您的数据,然后再渲染它们,如下所示
// we will restructure the array to look like the following
[
"Vehicle" => [
"Self-Propelled" => [
0 => "Infantry fighting.",
1 => "Cavalry fighting",
2 => "Armored personnel",
3 => "aerial tramway",
4 => "baby carriage",
5 => "delivery truck",
6 => "Nissan LEAF.",
7 => "Earth mover",
],
"Electric" => [
0 => "Audi A3 Sportback.",
1 => "BMW i3",
2 => "Chevrolet Bolt",
3 => "Chrysler Pacifica PHEV.",
4 => "Ford Fusion Energi.",
5 => "Hyundai IONIQ Electric.",
6 => "Mercedes GLE 550e.",
7 => "Ford F",
8 => "Mitsubishi/Nissan",
]
],
"Passageiro" => [
"Self-Propelled" => [
0 => "Armored reconnaissance",
]
],
]
// first restructure the array
$restructuredArray = [];
foreach ($array as $jsonData) {
$data = json_decode($jsonData);
$restructuredArray[$data->GROUP] = $restructuredArray[$data->GROUP] ?? [];
$restructuredArray[$data->GROUP][$data->BREED] = $restructuredArray[$data->GROUP][$data->BREED] ?? [];
$restructuredArray[$data->GROUP][$data->BREED][] = $data->NAME;
}
// second rendering the restructured array
foreach ($restructuredArray as $group => $breeds) {
echo "<h1>{$group}</h1>";
foreach($breeds as $breed => $names) {
echo "<h3>{$breed}</h3>";
foreach($names as $name) {
echo "<p>{$name}</p>";
}
}
}
建议 如果您可以控制数据库,最好以更好的格式或结构保存数据,在您的情况下,您可以使用 SQL(如 MySQL 使用关系)或 NoSQL(基于文档的数据库,如 MongoDB),两者都适合为您的需要。
- 2 回答
- 0 关注
- 208 浏览
添加回答
举报