Skip to content

Instantly share code, notes, and snippets.

@tjnicolaides
Created February 3, 2012 04:51
Show Gist options
  • Save tjnicolaides/1728150 to your computer and use it in GitHub Desktop.
Save tjnicolaides/1728150 to your computer and use it in GitHub Desktop.
Group array objects by closest start and end dates
<?php
// function described in greater detail here:
// http://stackoverflow.com/questions/8492458/whats-the-best-logic-for-grouping-objects-by-closest-start-and-end-dates
function cmp($a, $b){
return strcmp($a['start'], $b['start']);
}
$query = array(array('name' =>'A','start' =>'1/1/2011','end' =>'1/31/2011'),array('name' =>'B','start' =>'1/15/2011','end' =>'1/31/2011'),array('name' =>'C','start' =>'2/1/2011','end' =>'2/28/2011'),array('name' =>'D','start' =>'2/2/2011','end' =>'2/28/2011'),array('name' =>'E','start' =>'1/31/2011','end' =>'3/1/2011'), array('name' =>'F','start' =>'3/3/2011','end' =>'3/31/2011'));
usort($query, "cmp"); // organize by start date
$result = array();
$c = count($query);
for($i = 1; $i <= $c; $i++) {
if (empty($result)) {
$result[0][0] = $query[0];
unset($query[0]);
$query = array_values($query);
} else {
$lastkey_group = array_pop(array_keys($result));
$lastkey_object = array_pop(array_keys($result[$lastkey_group]));
// get the last object's end date
$last_end_date = strtotime($result[$lastkey_group][$lastkey_object]['end']);
$match_days = 1000;
$match_key = 1000;
foreach($query as $key => $q) {
$this_start_date = strtotime($q['start']);
$diff = round(($this_start_date - $last_end_date)/86400);
// compare to start date in each $q
if($diff < $match_days && $diff > 0) {
// if the distance is greater than 0 but less than $diff,
// replace match with distance and row key
$match_days = $diff;
$match_key = $key;
}
}
if($match_key == 1000) {
$result[$lastkey_group + 1][0] = $query[0]; // no good matches. write to a new group
unset($query[0]);
$query = array_values($query);
} else {
$result[$lastkey_group][$lastkey_object + 1] = $query[$match_key];
// match. write to this group
unset($query[$match_key]);
$query = array_values($query);
}
}
}
var_dump($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment