dongpu42006096 2018-11-02 14:31
浏览 131
已采纳

如何将一天中的时间分成3个桶:早上,下午和晚上?

I'm looking to count values from an array that contain a certain number. Basically, I'm looking to plot a graph os visits, and want to do it as 'morning', 'afternoon' and 'evening'. So I want to count times, such as 17:38 as 17, then count them so I can classify if visits were morning, afternoon or evening.

$time_array = array("17:45","13:12","09:29","17:32","16:49","14:18");

$counts = array_count_values($time_array);
$morning_counts = $counts['09'] + $counts['10'] + $counts['11'];
$afternoon_counts = $counts['12'] + $counts['13'] + $counts['14'] + $counts['15'] + $counts['16'];
$evening_counts = $counts['17'] + $counts['18'] + $counts['19'] + $counts['20'] + $counts['21'] + $counts['22'] + $counts['23'];

Expected output from sample data:

$morning_counts = 1
$afternoon_count = 3
$evening_counts = 2
  • 写回答

7条回答 默认 最新

  • doujiao3016 2018-11-02 14:36
    关注

    You can do this by creating counter variables. We can then create ranges of time frames using range(). Then get the values before the : in the time string as the hour and then compare that against the range, if it's in the range, add 1 to the counter.

    <?php
        $time_array = array("17:45","13:12","09:29","17:32","16:49","14:18");
    
        # create counter vars
        $mornCount = 0;
        $afternoonCount = 0;
        $eveCount = 0;
    
        # create range of times to compare against
        $mornRange = range(0, 11);
        $afternoonRange = range(12, 16);
        $eveRange = range(17, 23);
    
        foreach ($time_array as $time)
        {
            $compareTimeArr = explode(':', $time); # get first two chars of time
            $compareTime = $compareTimeArr[0];
    
            if (in_array($compareTime, $mornRange)) {
                $mornCount++;
            } elseif (in_array($compareTime, $afternoonRange)) {
                $afternoonCount++;
            } elseif (in_array($compareTime, $eveRange)) {
                $eveCount++;
            }
        }
    
        echo '<pre>'. print_r($mornCount,1) .'</pre>';
        echo '<pre>'. print_r($afternoonCount,1) .'</pre>';
        echo '<pre>'. print_r($eveCount,1) .'</pre>';
    

    refs:

    https://secure.php.net/manual/en/function.in-array.php

    https://secure.php.net/manual/en/function.explode.php

    https://secure.php.net/manual/en/function.range.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行