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条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器