0

アイテムを含む結果をループしようとしています。アイテムにはタイプがあり、各グループのカテゴリ タイトルをエコーアウトしようとしています。通常、これは 1 つのループでうまく機能しますが、私が考える$item-type foreach はうまくいきません。解決策はありますか?

<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
4

2 に答える 2

1

$subtypeifステートメントの前にNullに設定されていたため、果たす役割はありません。

$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>");
}
于 2012-10-16T00:52:19.013 に答える
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;?>
于 2012-10-16T02:55:56.843 に答える