doutenglou6588 2019-03-28 10:14 采纳率: 0%
浏览 154

如何遍历多个日期数组并组合相同日期的值

I have an Array wich outputs are the following Strings: Date(Datetime), Duration(Time). There are Multiple same days with different times.

For Example:

2019-03-04 00:00:00 |
 01:00:00

2019-03-04 00:00:00 | 
 00:05:00

2019-03-05 00:00:00 | 
 00:30:00

2019-03-05 00:00:00 | 
 00:15:00

Now I want to look for the same days and add all the Time Values for each day into one Time String.

My code looks something like this (simplified):

$sql_query = "SELECT date, time_in_minutes FROM user;
$result_sql = $db->query($sql_query);

while($sql_query = $result_sql->fetchrow(DB_FETCHMODE_ASSOC)) 
    {   
        echo $row_employee_data['date'];
        echo "<br/>";
        echo $row_employee_data['time_in_minutes'];
        echo "<br/>";
        echo "<br/>";

    }   

/*
Output: 
    2019-03-05 00:00:00

    00:15:00
*/

THe expected output should be an Multidimensional array wich outputs all Dates once with the other value beeing the Duration Time added together. For example:

2019-03-04 00:00:00

01:05:00

2019-03-05 00:00:00

00:45:00

  • 写回答

1条回答 默认 最新

  • douye1940 2019-03-28 10:21
    关注

    I have taken a static array with your provided values.

    So, you need to convert it to use it.

    We can simply take a multi-dimensional array.

    The keys would be dates and the sub arrays should contain respective times.

    For taking dates and times from strings, we will use php substr() function.

    Following is the code:

    <?php
    $dates = [];
    $dates[] = '2019-03-04 00:00:00 | 01:00:00';
    $dates[] = '2019-03-04 00:00:00 | 00:05:00';
    $dates[] = '2019-03-05 00:00:00 | 00:30:00';
    $dates[] = '2019-03-05 00:00:00 | 00:15:00';
    $output = [];
    if (! empty($dates)) {
     foreach ($dates as $date) {
      $temp = explode(' | ', substr($date, 11));
      $output[substr($date, 0, 10)][] = $temp;
     }
    }
    if (! empty($output)) {
     foreach ($output as $date => $time) {
       echo "<br/>" . $date;
       if (! empty($time)) {
          foreach ($time as $timeVal) {
            if (! empty($timeVal)) {
              foreach ($timeVal as $final) {
               echo "<br/>--" . $final;
                  }
                }
          }
        }
        echo "<hr/>";
     }
    }
    ?>
    

    And the Output:

    2019-03-04
    --00:00:00
    --01:00:00
    --00:00:00
    --00:05:00
    2019-03-05
    --00:00:00
    --00:30:00
    --00:00:00
    --00:15:00
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?