根据共享时间范围将二维数组数据格式化为连字符连续日期范围的字符串
我从 API 获得的数据的格式相当难以使用(以必需使用的方式)——我没有能力修改 API。下面是我得到的数据的示例:
$data = array(
array('day' => 'Monday', 'start' => 1100, 'end' => 1300),
array('day' => 'Tuesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Wednesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Thursday', 'start' => 1200, 'end' => 1300),
array('day' => 'Friday', 'start' => 1200, 'end' => 1300),
array('day' => 'Saturday', 'start' => 1200, 'end' => 1300),
array('day' => 'Sunday', 'start' => 1200, 'end' => 1400)
);
数据可能不包括一周中的所有 7 天,开始和结束在 0000 到 2400 之间变化。我试图想出一种使用以下输出格式化数据的方法:
Monday - Wednesday (1100-1300), Thursday - Saturday (1200-1300), Sunday (1200-1400)
基本上,连续的日期(其开始时间和结束时间相同)由连字符分隔。
我有点试图避免一大堆丑陋的代码。
I am given data from an API in a format that is pretty difficult to use (in the manner that is necessary to be used in) - I do not have the ability to modify the API. Below is an example of the data I am given:
$data = array(
array('day' => 'Monday', 'start' => 1100, 'end' => 1300),
array('day' => 'Tuesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Wednesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Thursday', 'start' => 1200, 'end' => 1300),
array('day' => 'Friday', 'start' => 1200, 'end' => 1300),
array('day' => 'Saturday', 'start' => 1200, 'end' => 1300),
array('day' => 'Sunday', 'start' => 1200, 'end' => 1400)
);
The data may not include all seven days of the week, start and end vary between 0000 and 2400. I am trying to come up with a way to format the data with the following output:
Monday - Wednesday (1100-1300), Thursday - Saturday (1200-1300), Sunday (1200-1400)
Basically, contiguous days (whose start and end times are the same) are separated by a hyphen.
I am kind of trying to avoid a huge block of ugly code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
丑陋是情人眼里出西施。 ;)我认为这没关系,但当然这可能正是您想要避免的。
会输出:
Ugliness is in the eye of the beholder. ;) I think this is OK, but of course it might be exactly what you're trying to avoid.
Would output:
在循环遍历行时,无条件地尝试写入或覆盖与当前星期几相同的小时范围(如果位于字符串)之前的单词。如果替换尝试失败,请将当前日期和时间范围附加到字符串末尾。
该脚本的优点是不需要预先对数据进行分组,然后再次循环以呈现分组的数据。这种方法只是一个注入或串联过程。 Demo
正则表达式模式:
如果上面的脚本不够漂亮或不够直观,也许可以声明更多变量来实现它更具表现力。
While looping over the rows unconditionally attempt to write or overwrite the word before the identical hour range (if at the string) with the current day of the week. If that replacement attempt fails, append the current day and time range to the end of the string.
This script has the benefit of not needing to pre-group the data and then loop again to present the grouped data. This approach is only an injection or concatenation process. Demo
The regex pattern:
If the above script isn't pretty or intuitive enough, maybe declare more variables to make it more expressive.