基于匹配小时数的组天数

时间:2015-12-11 11:31:44

标签: php arrays grouping

我如何在PHP中编写一个函数来合并具有类似商店营业时间的日子。例如,如果我们有:

Mon  : 9:00AM - 7:00PM
Tue  : 9:00AM - 10:00PM
Wed  : 9:00AM - 7:00PM
Thu  : 9:00AM - 10:00PM
Fri  : 9:00AM - 7:00PM
Sat  : 9:00AM - 10:00PM
Sun  : 9:00AM - 7:00PM

我希望代码输出为:

Mon,Wed,Fri,Sun - 9:00AM - 7:00PM
Tue,Thu,Sat - 9:00AM - 10:00PM

以下是我尝试解决的代码。

$openHours = array(
    'Mon' => '9am-7pm',
    'Tue' => '9am-10pm',
    'Wed' => '9am-7pm',
    'Thu' => '9am-10pm',
    'Fri' => '9am-7pm',
    'Sat' => '9am-10pm',
    'Sun' => '9am-7pm'
);

$summary = array();
foreach ($openHours as $day => $hours) {
    if (!array_key_exists($hours, $summary))
        $summary[$hours] = array($day);
    else
        $summary[$hours][] = $day;
}

foreach ($summary as $hours => $days) {
    echo array_shift($days) . '-' . array_pop($days) . ' ' . $hours . PHP_EOL;
}

2 个答案:

答案 0 :(得分:0)

这应该适合你:

首先,我们更改数组结构,并使用时间作为键,将天数作为值使用此代码:

foreach($openHours as $k => $v)
    $array[$v][] = $k;

所以我们最终得到一个像这样的数组结构:

Array
(
    [9am-7pm] => Array
        (
            [0] => Mon
            [1] => Wed
            [2] => Fri
            [3] => Sun
        )

    [9am-10pm] => Array
        (
            [0] => Tue
            [1] => Thu
            [2] => Sat
        )

)

之后我们只需要循环遍历新数组并将implode()天数循环到以逗号分隔的字符串,并在其后添加时间。

代码:

<?php

    $openHours = array(
        'Mon' => '9am-7pm',
        'Tue' => '9am-10pm',
        'Wed' => '9am-7pm',
        'Thu' => '9am-10pm',
        'Fri' => '9am-7pm',
        'Sat' => '9am-10pm',
        'Sun' => '9am-7pm'
    );


    foreach($openHours as $k => $v)
        $array[$v][] = $k;

    foreach($array as $time => $days)
        echo implode(",", $days) . " " . $time . PHP_EOL;

?>

输出:

Mon,Wed,Fri,Sun 9am-7pm
Tue,Thu,Sat 9am-10pm

答案 1 :(得分:-2)

  

$ closetime = [&#39; 7:00&#39; =&gt; [&#39;周一&#39;&#39;周三&#39;&#39;周五&#39;,&# 39;阳光&#39;]   &#39; 10:00&#39; =&GT; [&#39;星期二&#39;&#39;周四&#39;&#39;星期六&#39;]];

     

foreach($ closetime为$ time =&gt; $ days){echo explode(&#39;,&#39;,$ days)。&#34;    - 9:00 - &#34;。$ time; }

或类似的东西