PHP split data range to get only chunks free

后端 未结 1 1778
忘掉有多难
忘掉有多难 2021-01-22 21:55

I have a datarange in array for entire month:

$fullrange = array(
   \"start\" => \"2019-12-01 00:00:00\",
   \"end\" => \"2019-12-31 23:59:59\"
)
<         


        
1条回答
  •  再見小時候
    2021-01-22 22:49

    $startDateInTimestamp = \DateTime::createFromFormat('Y-m-d H:i:s', $fullrange['start'])->getTimestamp();
    $endDateInTimestamp  = \DateTime::createFromFormat('Y-m-d H:i:s', $fullrange['end'])->getTimestamp();
    function sortBy($a, $b, $value) {
        return \DateTime::createFromFormat('Y-m-d H:i:s', $a[$value])->getTimestamp() - \DateTime::createFromFormat('Y-m-d H:i:s', $b[$value])->getTimestamp();
    }
    
    function sortByStart($a, $b) 
    {
        return sortBy($a, $b, 'start');
    }
    function sortByEnd($a, $b) 
    {
        return sortBy($a, $b, 'end');
    }
    usort($array_activities, 'sortByStart');
    $index = 0;
    $final = [];
    $final[0]['startDate'] = date('Y-m-d H:i:s', $startDateInTimestamp);
    while (count($array_activities) > 0) {
        $array_activities = array_values($array_activities);
        $final[$index]['endDate'] = $array_activities[0]['start'];
        unset($array_activities[0]['start']);
        usort($array_activities, 'sortByEnd');
        $index++;
        $final[$index]['startDate'] = $array_activities[0]['end'];
        unset($array_activities[0]['end']);
        if(!isset($array_activities[0]['end']) && !isset($array_activities[0]['start']))     {
            unset($array_activities[0]);
        }
        usort($array_activities, 'sortByStart');
    }
    $final[count($final)-1]['endDate'] = date('Y-m-d H:i:s', $endDateInTimestamp);
    
    
    echo "
    ";
    print_r($final);
    echo "
    ";

    0 讨论(0)
提交回复
热议问题