title: How to group by and sum a multi-dimensional array?
body: <p>I have already seen <a href="https://stackoverflow.com/questions/2827501/php-how-to-sum-and-group-by-a-multidimensional-array-by-a-key">this
  stackoverflow page</a> but it is not helping me.</p>
  
  <p>I want to group by two columns and sum the values of a third column.</p>
  
  <p>If the <code>discount_id</code> and <code>dis_percent</code> are the same then add the <code>discount_value</code>. </p>
  
  <p>Here is my array:</p>
  
  <pre><code>$dis = [
      [['Dis_id' =&gt; 'Dl-Dis1'], ['Dis_per' =&gt; '7.500'], ['Dis_val' =&gt; '192.75']],
      [['Dis_id' =&gt; 'Dl-Dis2'], ['Dis_per' =&gt; '2.500'], ['Dis_val' =&gt; '97.88']],
      [['Dis_id' =&gt; 'Dl-Dis1'], ['Dis_per' =&gt; '5.000'], ['Dis_val' =&gt; '39.90']],
      [['Dis_id' =&gt; 'Dl-Dis2'], ['Dis_per' =&gt; '2.500'], ['Dis_val' =&gt; '99.90']]
  ];
  </code></pre>
  
  <p>The output that I need is:</p>
  
  <pre><code>D1-Dis1-&gt;7.5-&gt;192.75
  D1-Dis1-&gt;5.0-&gt;39.9
  D1-Dis2-&gt;2.5-&gt;197.78
  </code></pre>
  
  <p>My code looks like this:</p>
  
  <pre><code>$newarr = array();
  $reverse_map = array();
  
  foreach($dis as $idx =&gt; $entry) {
      if (isset($reverse_map[$entry['Dis_id']])) {
           // have we seen this name before? retrieve its original index value
           $idx = $reverse_map[$entry['Dis_id']]; 
      } else {
           // nope, new name, so store its index value
           $reverse_map[$entry['Dis_id']] = $idx;
      }
  
      // copy the 'constant' values
      $newarr[$idx]['Dis_id'] = $entry['Dis_id'];
      $newarr[$idx]['Dis_per'] = $entry['Dis_per'];
  
      // sum the qtd_post values to whatever we previously stored.        
      foreach($entry['Dis_val'] as $x =&gt; $y) {
          $newarr[$idx]['Dis_val'][$x] += $y;
      }
  }
  </code></pre>