2016-06-28 110 views
-1

在我的數據庫我的表結構是這樣的:遍歷類,childcategories和產品在樹枝

enter image description here

某些類別具有孩子類別,有些不是。一個產品可以屬於:

  • 兒童類
  • 父類(該類沒有子類別)

我的數組是這樣的:

enter image description here

範疇A是父類別。 B類 - 頭也是一個父類別。 B類 - 兒童是兒童類乙 - 頭。現在

我想顯示這個數組是這樣的:

enter image description here

但是我卡在如何知道它是否是一個類別或產品的列表。有人可以幫我弄這個嗎?

+0

的數據結構看起來並不理想的你想要什麼去做。父類別可以有最大數量的子類別嗎?例如,類別B下是否可以有另一個類別?或者一件物品只能在兩種類別下使用? – Shane

+0

@Shane,類別B - 頭下可能有另一個孩子類別。你會建議什麼結構? .. – nielsv

+0

一個類別可以同時具有子類別和產品嗎? – qooplmao

回答

1

如果您使用的是Doctrine Models(如果您使用的是Symfony,那麼您應該是),那麼您所做的只是循環遍歷對象上的方法。

幾乎沒有假設的快速和骯髒的例子,例如使用@Template()註解和標準的DAO又名的EntityManager [秒],以及具有的getChildren()和的getProducts()在Category.php(AKA模型/實體)方法

在控制器

/** 
* @Route("/products", name="all_products") 
* @Template() 
*/ 
public function someAction() 
{ 
    ... 
    $categories  = $this->getCategoryManager()->findBy([]); 
    ... 
    return [ 
     'categories' => $categories 
    ]; 
} 

在您的樹枝模板

{% if categories|length > 0 %} 
    {% for category in categories %} 
     {% if category.children|length > 0 %} 
     ... Here you create the HTML for nested ... 
     {% else %} 
      ... Here you create the HTML for Category ... 
      {% for product in category.products %} 
      ... Here you create the HTML for products ... 
      {% endfor %} 
     {% endif %} 
    {% endfor %} 
{% else %} 
    .... some html to handle empty categories .... 
{% endif %} 

如果HTML平(很可能出現的情況),重複嵌套的HTML,那麼你可以創建和包括宏吐出了這一點你。

這是基本的,但我認爲它幾乎涵蓋了你在問我是否正確理解你的問題。

順便說一句,你一定要閱讀小枝和Symfony的文檔,因爲他們有這樣的例子到處都是。

我會編輯此答案,如果您作出適當的響應。現在你還沒有發佈足夠的信息來真正指導你,但希望這有助於你。

0

你可以使用遞歸宏。在宏觀你要麼打印的產品清單或打印類別列表中,然後調用本身..等等...

{% macro navigation(categories, products) %} 
    {% from '_macros.html.twig' import navigation %} 

    {% if categories|length > 0 or products|length > 0 %} 
     <ul> 
      {% for category in categories %} 
       <li> 
        {{ category.name }} 
         ({{ category.children|length }} child(ren) &amp; {{ category.products|length }} products) 
        {{ navigation(category.children, category.products) }} 
       </li> 
      {% endfor %} 
      {% for product in products %} 
       <li>{{ product.name }}</li> 
      {% endfor %} 
     </ul> 
    {% endif %} 
{% endmacro %} 

你只像一個模板使用此...

{% from '_macros.html.twig' import navigation %} 

{{ navigation(array_of_categories) }} 

這只是創建一個基本的嵌套無序列表集,但可以用於任何你想要的HTML,顯然。

對於小提琴,請參閱http://twigfiddle.com/mzsq8z)。

小提琴呈現爲以下(twigfiddle只顯示HTLM,而不是東西,你可以用它來可視化)...

enter image description here