title: Algorithm to combine / merge date ranges
body: <p>I am trying to find the best way on how to merge date ranges into one database record (array element). </p>
  
  <p>This is the data I have: </p>
  
  <pre><code>  Array
  (
      [0] =&gt; Array
          (
              [id] =&gt; 18298
              [start_date] =&gt; 2011-07-09
              [end_date] =&gt; 2011-10-01
          )
  
      [1] =&gt; Array
          (
              [id] =&gt; 18297
              [start_date] =&gt; 2011-06-01
              [end_date] =&gt; 2011-06-30
          )
  
      [2] =&gt; Array
          (
              [id] =&gt; 17113
              [start_date] =&gt; 2011-03-31
              [end_date] =&gt; 2011-05-31
          )
  
      [3] =&gt; Array
          (
              [id] =&gt; 20555
              [start_date] =&gt; 2011-01-03
              [end_date] =&gt; 2011-03-31
          )
  )
  </code></pre>
  
  <p>And after we combine them, array (or database) should look like this:</p>
  
  <pre><code>Array
  (
      [0] =&gt; Array
          (
              [merged_ids] =&gt; 18298
              [start_date] =&gt; 2011-07-09
              [end_date] =&gt; 2011-10-01
          )
  
      [1] =&gt; Array
          (
              [merged_ids] =&gt; 18297, 17113, 20555
              [start_date] =&gt; 2011-01-03
              [end_date] =&gt; 2011-06-30
          )
  )
  </code></pre>
  
  <p>Is there any algorithm to go through all elements/ranges and combine them? Which way is better/easier to do - through database (MYSQL) or coding (PHP)?</p>
  
  <p>Any advise is highly appreciated.</p>
  
  <p>Thanks!</p>
  
  <p><strong>UPDATE:</strong> Sorry, I didn't provide enough info: we should merge any continuous and overlapping date ranges. </p>