我有一家商店的营业时间:
array:3 [▼
1 => array:2 [▼
"opens_at" => "10:00"
"closes_at" => "18:00"
]
2 => array:2 [▼
"opens_at" => "10:00"
"closes_at" => "18:00"
]
3 => array:2 [▼
"opens_at" => "10:00"
"closes_at" => "18:00"
]
4 => array:2 [▼
"opens_at" => "14:00"
"closes_at" => "17:00"
]
5 => array:2 [▼
"opens_at" => "14:00"
"closes_at" => "17:00"
]
6 => array:2 [▼
"opens_at" => "18:00"
"closes_at" => "19:00"
]
]
在这种情况下,数组从1到6的键是星期几(星期一至星期六),为此我使用了一个简单的Enum类:
class WeekDays
{
const MONDAY = 1;
const TUESDAY = 2;
const WEDNESDAY = 3;
const THURSDAY = 4;
const FRIDAY = 5;
const SATURDAY = 6;
const SUNDAY = 7;
}
所以,我需要得到一个将营业时间和营业时间相近的日期进行分组的结果,如下所示:
[
Mo,Tu,We 10:00-18:00,
Th,Fr 14:00-17:00
Sa 18:00-19:00
]
我无法弄清楚如何按opens_at
和closes_at
进行分组,以获得我所显示的任何格式化结果。预先感谢!
答案 0 :(得分:2)
这不是一个非常优雅的解决方案,但是它可以提示您如何自己解决问题:
<?php
$a = [
1 => [
"opens_at" => "10:00",
"closes_at" => "18:00"
],
2 => [
"opens_at" => "10:00",
"closes_at" => "18:00"
],
3 => [
"opens_at" => "10:00",
"closes_at" => "18:00"
],
4 => [
"opens_at" => "14:00",
"closes_at" => "17:00"
],
5 => [
"opens_at" => "14:00",
"closes_at" => "17:00"
],
6 => [
"opens_at" => "18:00",
"closes_at" => "19:00"
]
];
$groups = [];
foreach($a as $dayNumber => $w){
if(!array_key_exists($w['opens_at'] . '-' . $w['closes_at'], $groups)){
$groups[$w['opens_at'] . '-' . $w['closes_at']] = [];
}
$groups[$w['opens_at'] . '-' . $w['closes_at']][] = $dayNumber;
}
$res = array_map(function($v){
return implode(', ', $v);
}, $groups);
var_dump(array_flip($res));
结果:
array(3) { ["1, 2, 3"]=> string(11) "10:00-18:00" ["4, 5"]=> string(11) "14:00-17:00" [6]=> string(11) "18:00-19:00" }