PHP combine two seperate conflicting date ranges into unique pairs

后端 未结 3 404
陌清茗
陌清茗 2021-01-20 16:05

Set one:

  1. 2014-04-05 To 2014-06-27
  2. 2014-06-28 To 2014-10-19

Set two:

  1. 2014-04-05 To 2014-05-02
  2. 2014-05-03 To 2014
3条回答
  •  终归单人心
    2021-01-20 16:36

    Here is my solution:

    '2014-04-05','e'=>'2014-06-27'),
        array('s'=>'2014-06-28','e'=>'2014-10-19')
    );
    $array2 = array(
        array('s'=>'2014-04-05','e'=>'2014-05-02'),
        array('s'=>'2014-05-03','e'=>'2014-05-31'),
        array('s'=>'2014-06-01','e'=>'2014-10-19')
    );
    
    //merge arrays together
    $merged_array = array_merge($array1,$array2);
    
    //filter out duplicate start dates
    $filtered_array = array();
    foreach($merged_array as $k=>$v){
        if(!isset($filtered_array[ $v['s'] ] )){
            $filtered_array[ $v['s'] ] = $v;
        }
    
        //if the end date is before the currently saved end date (for this start date) then use it
        if( strtotime($v['e']) < strtotime($filtered_array[ $v['s'] ]['e']) ){
            $filtered_array[ $v['s'] ] = $v;
        }
    }
    
    //reset the array to zero based
    $filtered_array = array_values($filtered_array);
    
    //sort the array by start date
    $tmp = array();
    foreach($filtered_array as $k=>$v){
        $tmp[$k] = $v['s'];
    }
    
    array_multisort($tmp,SORT_ASC,$filtered_array);
    
    //end date overlap checking
    foreach($filtered_array as $k=>$v){
        //if the end date is after (or equal to) the "next" start date, then make that end date the "yesterday" of the next start date
        if( isset($filtered_array[$k+1]['s']) && strtotime($v['e']) >= strtotime($filtered_array[$k+1]['s'])  ){
            $yesterday = strtotime($filtered_array[$k+1]['s']) - 1;
            $yesterday = date("Y-m-d",$yesterday);
            $filtered_array[$k]['e'] = $yesterday;
        }
    }
    
    echo '
    ',print_r($filtered_array),'
    '; /* Array ( [0] => Array ( [s] => 2014-04-05 [e] => 2014-05-02 ) [1] => Array ( [s] => 2014-05-03 [e] => 2014-05-31 ) [2] => Array ( [s] => 2014-06-01 [e] => 2014-06-27 ) [3] => Array ( [s] => 2014-06-28 [e] => 2014-10-19 ) ) */

提交回复
热议问题