基于开始和结束时间的组周名称

时间:2015-08-19 12:07:21

标签: php arrays

我有一个像这样的数组

Array(
       [mon] => Array
    (
        [start] => 09
        [end] => 18
        [hours] => 9
    )

[tue] => Array
    (
        [start] => 09
        [end] => 18
        [hours] => 9
    )

[wed] => Array
    (
        [start] => 09
        [end] => 18
        [hours] => 9
    )

[thu] => Array
    (
        [start] => 09
        [end] => 18
        [hours] => 9
    )

[fri] => Array
    (
        [start] => 00
        [end] => 21
        [hours] => 21
    )

[sat] => 
[sun] => 
);

现在我的任务能够以简单的格式显示,如

Mon-Thu    Fri
09 - 18    00-21

那么我们如何将上面的数组转换为简单数组以在客户端显示所需的格式

我尝试了以下代码,但是它给出了日期分组,

  $workHours = $bhr->workingHours;
$days = array_keys($workHours);
$workHoursInfo = array_values($workHours);
$result = array();

for($i=0;$i<count($workHoursInfo);$i++){
    $info1 = $workHoursInfo[$i];
    if(empty($info1))            continue;
    for($j=1;$j<count($workHoursInfo);$j++) {
        $info2 = $workHoursInfo[$j];
        if(empty($info2))            continue;
        if($info1['start'] === $info2['start'] && $info1['end'] === $info2['end']) {
            if(!in_array($days[$i],$result)) {
                $result[] = $days[$i];
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个可以帮助你的功能。我已经添加了一些评论来帮助您完成我的工作。

$workhours = array(
    'mon' => array('start' => '09', 'end' => '18', 'hours' => '9'),
    'tue' => array('start' => '09', 'end' => '18', 'hours' => '9'),
    'wed' => array('start' => '09', 'end' => '18', 'hours' => '9'),
    'thu' => array('start' => '09', 'end' => '18', 'hours' => '9'),
    'fri' => array('start' => '00', 'end' => '21', 'hours' => '21'),
    'sat' => array(),
    'sun' => array(),
);


function format_workhours($workhours){
    $days = array_keys($workhours);

    $temp = array();
    // group by start and end hours
    foreach($workhours as $day => $hours){
        if(isset($hours['start'])){
            $temp[$hours['start'] . '-' . $hours['end']][] = $day;
        }
    }

    // echo with , or - 
    foreach($temp as $i => $work){
        $first = reset($work);
        // Only 1 day so just print it
        if (count($work) === 1){
            echo $first . ': ' . $i . '<br>';
            continue;
        }
        $pos = array_search($first,$days);
        $array = array_slice($days,$pos,count($temp[$i]));
        // all days follow on each other so use a dash
        if($temp[$i] === $array){
            $last = end($work);
            echo $first . '-' . $last . ':' . $i . '<br>';
        }else{ // print all days with a comma
            $workdays = implode(',',$work);
            echo $workdays . ':' . $i . '<br>';
        }
    }
}

format_workhours($workhours);

输出:

周一:09-18 星期五:00-21