尝试循环通过具有项目的结果。项目具有类型并尝试回显每个组的类别标题。通常情况下,这对于一个循环来说非常好,但$ item-type foreach I Think 正在抛弃它。任何解决方案?
<h2>Package <?=$packages->id?></h2>
<?php foreach($packages->item as $item):?>
<?php foreach($item->type as $type):?>
<?php $subtype = null;?>
<?php if($subtype != $type->name)?>
<h3><?=$type->name?></h3>
<?=$item->name?><br>
<?php $subtype = $type->name;?>
<?php endforeach;?>
<?php endforeach;?>
数据库结构:
items
id name
1 mainitem1
2 mainitem2
3 item1
4 item2
5 item3
6 item4
types
id name
1 category 1
2 category 2
3 subcategory1
4 subcategory2
item_type
id item_id type_id
1 1 1
2 2 2
3 3 3
4 4 3
5 5 4
6 6 4
packages
id item_id
1 1
2 2
item_package
id package_id item_id
1 1 3
2 1 5
3 2 4
4 2 6
我目前的结果是:
package 1
category 1
item 3
category 1
item 5
category 2
item 4
category 2
item 6
期望的结果:
package 1
category 1
item 3
item 5
category 2
item 4
item 6
答案 0 :(得分:1)
$subtype
没有任何角色可以玩,因为它在if语句
$subtype = null;
if($subtype != $type->name) <------- This would always be true
类别名称也是重复的,因为它在内部循环中而不是外部循环
这就是我认为你需要的全部
printf("<h2>%s</h2>", $packages->id);
foreach ( $packages->item as $item ) {
printf("<h3>%s</h3>", $type->name);
print("<ul>");
foreach ( $item->type as $type ) {
printf("<li>%s</li>", $item->name);
}
print("</ul>");
}
答案 1 :(得分:1)
作为上述问题的解决方案,请参阅以下代码段
<h2>Package <?=$packages->id?></h2>
<?php foreach($packages->item as $item):?>
<h3><?php echo $item->name;?></h3>
<?php foreach($item->type as $type):?>
<?php $subtype = null;?>
<?php if($subtype != $type->name)?>
<?=$type->name?><br>
<?php $subtype = $type->name;?>
<?php endforeach;?>
<?php endforeach;?>