php 如何在数组中对时间进行分组

fcipmucu  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(204)

我在PHP中有以下数组:

$time = array("09:00AM","09:05AM","09:10AM","09:15AM","09:20AM","09:30AM","12:15PM", "12:20PM", "12:25PM","15:30PM","15:35PM","15:40AM","15:45AM","15:50PM");

我如何回应下面的格式?有人知道这是否可行吗?

09:00AM - 09:30AM
12:15PM - 12:25PM
15:30PM - 15:50PM

我对阵的理解还需要练习。
我试图寻找解决方案,但没有找到任何地方这样做

nukf8bse

nukf8bse1#

抱歉,这是我的更新脚本:$time =数组(“9:00”、“9:05”、“9:10”、"9:15”、“9:20”、“9:30”、“12:15”、“12:20”、“12:25”、“15:30”、“15:35”、“15:40”、“15:45”、“15:50”);...
基于以上(您的最后一条评论),您可以得到以下结果:

09:00 -- 09:30
12:15 -- 12:25
15:30 -- 15:50

具体代码如下:

<?php

$time = Array(
            "09:00","09:05","09:10","09:15","09:20","09:30",
            "12:15", "12:20", "12:25",
            "15:30","15:35","15:40","15:45","15:50"
);

$map = Array();
$prev = "";

foreach ($time as $t) {
    $dt = date_create_from_format("H:i", $t);
    $hr = date_format($dt,"H");
    $mi = date_format($dt,"i");
    if ($prev !== $hr) {
        $map[$hr] = Array($mi);
        $prev = $hr;
    }
    else {
        $map[$hr][] = $mi;
    }   
}

foreach ($map as $k => $v) {
    // sort($v); // this is optional
    $first = $v[0];
    $last = $v[count($v) - 1];
    echo "$k:$first -- $k:$last" . "<br>";
}

?>

请注意,此代码可能会被精炼为简洁。

相关问题