2012-10-16 50 views
0

试图循环通过项目的结果。项目有一个类型,并试图回显每个组的分类标题。通常情况下,这在一个循环中效果很好,但$ item-type foreach I Think正在抛弃。任何解决方案PHP Foreach循环与If如果

<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;?> 

DB结构:

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 
+1

你可以'print_r($ packages-> item)'代替 – Baba

+0

预先格式化了其大约1000行 – dynamo

+0

将其添加到粘贴bin ..想要确定在这里处理的是什么 – Baba

回答

1

$subtype没有发挥作用,因为它被设置在此之前为空如果E声明

$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>"); 
} 
+0

@dynamo看到这个代码会为你工作..试试看 – Baba

+0

这仍然给我同样的结果,请用我的pastebin查看我的评论。 – dynamo

+0

@dynamo让我用你的真实对象工作,然后添加'serialize($ packages)'过去bin ..我将能够直接使用你的对象 – Baba

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;?>