匹配的日子和时间

时间:2016-01-18 06:01:04

标签: php arrays days hour

我想从此分组日期和时间:

Mon  : array(9:00AM - 11:00AM, 1:00pm-6pm)
Tue  : array(8:00AM - 11:00AM,12:00pm-6pm)
Wed  : array(9:00AM - 11:00AM, 1:00pm-6pm)
Thu  : array(9:00AM - 11:00AM,1:00pm-6pm)
Fri  : array(9:00AM - 12:00PM,1:00pm-6pm)
Sat  : array(9:00AM - 7:00PM)
Sun  : array(9:00AM - 12:00AM,1:00pm-6pm)

预期结果:

Mon,wed,thu - 9:00AM - 11:00aM
              1:00pm-6pm
tue :         8:00AM - 11:00am
              12:00pm-6pm   
fri,sun -     9:00AM - 12:00PM
              1:00pm-6pm
sat:          9:00AM -7:00pm
Below is the code which I'm trying to work out.

    $open_Hours = array(
            'Mon' => array('9:00AM - 11:00AM', '1:00pm-6pm'),
            'Tue' =>array('8:00AM - 11:00AM', '12:00pm-6pm'),
            'Wed' =>  array('9:00AM - 11:00AM', '1:00pm-6pm'),
            'Thu' => array('9:00AM - 11:00AM','1:00pm-6pm'),
            'Fri' => array('9:00AM - 12:00PM','1:00pm-6pm'),
            'Sat' => array('9:00AM - 7:00PM'),
            'Sun' => array('9:00AM - 12:00AM','1:00pm-6pm')
        );

     foreach($open_Hours as $k => $v){

            $open_array[$v][] = $k;
        }
     foreach($open_array as $time => $days){

             echo implode(",", $days) . " " . $time . PHP_EOL;

     }

1 个答案:

答案 0 :(得分:2)

这是我想出的。

<?php
    $open_Hours = array(
        'Mon' => array('9:00AM - 11:00AM', '1:00pm - 6pm'),
        'Tue' => array('8:00AM - 11:00AM', '12:00pm - 6pm'),
        'Wed' => array('9:00AM - 11:00AM', '1:00pm - 6pm'),
        'Thu' => array('9:00AM - 11:00AM','1:00pm - 6pm'),
        'Fri' => array('9:00AM - 12:00PM','1:00pm - 6pm'),
        'Sat' => array('9:00AM - 7:00PM'),
        'Sun' => array('9:00AM - 12:00PM','1:00pm - 6pm')
    );

    $open_array = array();
    foreach($open_Hours as $day => $periods) {
        if(!isset($open_array[serialize($periods)]))
            $open_array[serialize($periods)] = array();
        $open_array[serialize($periods)][] = $day;
    }

    foreach($open_array as $times => $days) {
        $times = unserialize($times);
        $days = implode(",", $days);
        for($i=0;$i<count($times); $i++) {
            if($i == 0) {
                echo $days;
                echo str_repeat(' ', ((strlen($days)>12)?0:(12-strlen($days)));
            } else {
                echo str_repeat(' ', 12);
            }
            echo '- ' . $times[$i] . PHP_EOL;
        }
    }

输出:

Mon,Wed,Thu - 9:00AM - 11:00AM
            - 1:00pm - 6pm
Tue         - 8:00AM - 11:00AM
            - 12:00pm - 6pm
Fri,Sun     - 9:00AM - 12:00PM
            - 1:00pm - 6pm
Sat         - 9:00AM - 7:00PM

它使用serialize()作为数组索引,以便您可以正确地按多个小时组进行分组。

如果您需要任何进一步的帮助或解释,请与我们联系。