title: Group array based on key
body: <p>I have an array that is fetched from my database. This is the result returned.  </p>
  
  <pre><code>Array
  (
      [0] =&gt; stdClass Object
          (
              [id] =&gt; 4
              [productID] =&gt; bla123
              [rating] =&gt; 2
              [username] =&gt; 
              [image] =&gt; black-468-sir-corbett-9-400x400-imadxbb7hyhkgvpc.jpeg
          )
  
      [1] =&gt; stdClass Object
          (
              [id] =&gt; 5
              [productID] =&gt; 12xye
              [rating] =&gt; 4
              [username] =&gt; 
              [image] =&gt; black-602-unistar-5-400x400-imaeffn5mytbruum.jpeg
          )
  
      [2] =&gt; stdClass Object
          (
              [id] =&gt; 6
              [productID] =&gt; bla123
              [rating] =&gt; 2
              [username] =&gt; 
              [image] =&gt; black-468-sir-corbett-9-400x400-imadxbb7hyhkgvpc.jpeg
          )
  
      [3] =&gt; stdClass Object
          (
              [id] =&gt; 7
              [productID] =&gt; 12xye
              [rating] =&gt; 4
              [username] =&gt; 
              [image] =&gt; black-602-unistar-5-400x400-imaeffn5mytbruum.jpeg
          )
  )
  </code></pre>
  
  <p>I would like to Group this data base on product key. So that I would get a an array with product id and its corresponding values like its images and its rating in an array. This is basically for an rating system, product and its rating. </p>
  
  <p>If the above is not practical, can you please suggest me some way in which I  can display all products with its image and its corresponding rating like one star:1 two star:3 three star:2 etc from the above data.</p>
  
  <p>I tried like this </p>
  
  <pre><code>foreach($ratings as $value) {
             $productID = $value-&gt;productID;
             if(isset($result[$productID])){
              $result[$productID][] = $value-&gt;rating;
             } else {
                   $result[$productID] = array();
              }
          }
  </code></pre>
  
  <p>from the above code I will get </p>
  
  <pre><code>Array
  (
      [bla123] =&gt; Array
          (
              [0] =&gt; 2
              [1] =&gt; 3
              [2] =&gt; 2
              [3] =&gt; 2
              [4] =&gt; 2
              [5] =&gt; 2
              [6] =&gt; 2
              [7] =&gt; 2
              [8] =&gt; 2
          )
  
      [12xye] =&gt; Array
          (
              [0] =&gt; 4
              [1] =&gt; 3
              [2] =&gt; 3
              [3] =&gt; 2
              [4] =&gt; 2
              [5] =&gt; 4
              [6] =&gt; 2
              [7] =&gt; 2
              [8] =&gt; 2
          )
  
  )
  </code></pre>
  
  <p>The problem is I also need to add the image to this, which I am finding really hard to do. </p>