title: Magento Event Observer to group product collection by category
body: <p>I'm creating an events observer module which will group upsell products by category,</p>
  
  <p>below is my module's model/observer.php file,</p>
  
  <pre><code>public function updateUpsells($observer)
      {
          $iCurrentCategory = Mage::registry('current_category')-&gt;getId();
          $event = $observer-&gt;getEvent();
          $oUpsellCollection = $event-&gt;getCollection();
          foreach ($oUpsellCollection-&gt;getItems() as $key =&gt; $oUpsellProduct) {
              $aCategoriesIds = $oUpsellProduct-&gt;getCategoryIds();
              if (!in_array($iCurrentCategory, $aCategoriesIds)) {
                  $oUpsellCollection-&gt;removeItemByKey($key);
              }
          }
      }
  }
  </code></pre>
  
  <p>After enabling this module i can include <code>upsell product's category id's</code> in <code>upsell.phtml</code> file by echo <code>$this-&gt;getItemCollection()-&gt;getItems()</code></p>
  
  <p>as a result i got,</p>
  
  <pre><code>    Array
  (
      [170] =&gt; Mage_Catalog_Model_Product Object
          ( 
             .........................
             [_data:protected] =&gt; Array
                  (
                      [entity_id] =&gt; 170
                      [entity_type_id] =&gt; 10
                      [attribute_set_id] =&gt; 44
                      [type_id] =&gt; simple
                      [category_ids] =&gt; Array
                          (
                              [0] =&gt; 12
                              [1] =&gt; 26
                          )
                      .......................
  
             )
      [171] =&gt; Mage_Catalog_Model_Product Object
          ( 
             .........................
             [_data:protected] =&gt; Array
                  (
                      [entity_id] =&gt; 171
                      [entity_type_id] =&gt; 10
                      [attribute_set_id] =&gt; 44
                      [type_id] =&gt; simple
                      [category_ids] =&gt; Array
                          (
                              [0] =&gt; 16
                              [1] =&gt; 24
                          )
                      .......................
  
             )
  )
  </code></pre>
  
  <p>So now how can i group this array results by category. Example mentioned 2 upsell products assigned to 4 different categories, as a result i need to group products like,</p>
  
  <pre><code>Category id 12
    product1 | Product2
  
  Category id 26
    product1 | Product2
  </code></pre>