你可以试试这个...
你的阵列
$array = array(
"Mon" => 0.40,
"Tue" => 0.40,
"Wed" => 0.40,
"Thu" => 0.40,
"Fri" => 0.40,
"Sat" => 0.50,
"Sun" => null);
示例 1
var_dump(groupDateTime($array));
输出
array
0 =>
array
's' => string 'Mon' (length=3)
'e' => string 'Fri' (length=3)
't' => float 0.4
1 =>
array
's' => string 'Sat' (length=3)
'e' => string 'Sat' (length=3)
't' => float 0.5
示例 2
var_dump(groupDateTime($array,true));
^---------- Optional Formatting
输出
array
0 => string 'Mon - Fri 0.4' (length=13)
1 => string 'Sat 0.5' (length=7)
使用的功能
function groupDateTime($array, $format = false) {
$group = array();
$x = 0;
foreach ( $array as $day => $time ) {
if (empty($group[$x]) === true) {
$group[$x]['s'] = $day;
$group[$x]['e'] = $day;
$group[$x]['t'] = $time;
}
if ($group[$x]['t'] === $time) {
$group[$x]['e'] = $day;
continue;
}
$x ++;
$group[$x]['s'] = $day;
$group[$x]['e'] = $day;
$group[$x]['t'] = $time;
}
$group = array_filter($group, function ($v) {
return ! empty($v['t']);
});
if ($format === true)
$group = array_map(function ($v) {
if ($v['s'] == $v['e'])
return "{$v['s']} {$v['t']}";
return "{$v['s']} - {$v['e']} {$v['t']}";
}, $group);
return $group;
}