我有这个数组,其中天是关键,时间是值:
Array(
[Mon] => 9:00-10:00,12:00-15:00,10:00-14:00
[Tue] => 9:00-10:00,12:00-15:00
[Wed] => 9:00-10:00,12:00-15:00
[Thu] => 9:00-10:00,12:00-15:00
[Fri] => 9:00-10:00,12:00-15:00
[Sat] => 9:00-10:00,12:00-15:00
[Sun] => 10:00-14:00
)
我想以这种方式使用相同的数组:
Array(
[Mon] => 9:00-10:00,12:00-15:00,10:00-14:00
[Tue/Wed/Thu/Fri/Sat] => 9:00-10:00,12:00-15:00
[Sun] => 10:00-14:00
)
任何人都能帮助我吗?
答案 0 :(得分:1)
可能有更好的方法来实现这一目标,但以下情况应该有效: -
$input = <YOUR ARRAY>
$output = array();
foreach ($input as $k => $v) {
if (!isset($output[$v])) {
$output[$v] = $k;
} else {
$output[$v] .= '/' . $k;
}
}
print_r(array_flip($output));
答案 1 :(得分:0)
$temp = array();
foreach ($array as $day => $value) {
if (!in_array($value, $temp)) {
$temp[] = $value;
$result[implode("/",array_keys($array,$value))] = $value;
}
}
请参阅DEMO。
答案 2 :(得分:0)
$data = array(
'Mon' => '9:00-10:00,12:00-15:00,10:00-14:00',
'Tue' => '9:00-10:00,12:00-15:00',
'Wed' => '9:00-10:00,12:00-15:00',
'Thu' => '9:00-10:00,12:00-15:00',
'Fri' => '9:00-10:00,12:00-15:00',
'Sat' => '9:00-10:00,12:00-15:00',
'Sun' => '10:00-14:00'
);
$new_data = array();
foreach($data as $key => $value){
$index = array_search($value, $new_data);
if($index){
$new_data[$index .'/' . $key] = $value;
unset($new_data[$index]);
}else{
$new_data[$key] = $value;
}
}
echo '<pre>';
var_dump($new_data);
echo '</pre>';
答案 3 :(得分:0)
所以,这是我的长篇例子。
$date_array = Array(
'Mon' => '9:00-10:00, 12:00-15:00, 10:00-14:00',
'Tue' => '9:00-10:00, 12:00-15:00',
'Wed' => '9:00-10:00, 12:00-15:00',
'Thu' => '9:00-10:00, 12:00-15:00',
'Fri' => '9:00-10:00, 12:00-15:00',
'Sat' => '9:00-10:00, 12:00-15:00',
'Sun' => '10:00-14:00',
);
$previous = null;
$new_days = array();
$new_times = array();
$i = 0;
foreach ($date_array as $day => $time) {
if ($time === $previous) {
$new_days[$i] .= '/' . $day;
$new_times[$i] = $time;
} else {
$i++;
$new_days[$i] = $day;
$new_times[$i] = $time;
}
$previous = $time;
}
var_dump(array_combine($new_days, $new_times));
答案 4 :(得分:0)
重新查看您的问题后,我找到了以下解决方案,基本上使用foreach
并使用该值汇总天数作为收集日期的关键字(第一个foreach);然后将天数打入单个字符串(第二个foreach),然后翻转数组:
$output = array();
foreach ($input as $day => $time) $output[$time][] = $day;
foreach ($output as &$value) $value = implode('/', $value);
unset ($value);
print_r(array_flip($output));