2012-10-16 75 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;?>