0

我有这个数组,其中天是关键,时间是值:

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

)

任何人都可以帮助我吗?

4

5 回答 5

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));

这是一个工作示例

于 2013-04-05T12:12:02.813 回答
0
$temp = array();
foreach ($array as $day => $value) {
    if (!in_array($value, $temp)) {
        $temp[] = $value;
        $result[implode("/",array_keys($array,$value))] = $value;
    }
}

演示

于 2013-04-05T12:13:11.330 回答
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>';
于 2013-04-05T12:14:30.510 回答
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));
于 2013-04-05T12:16:27.637 回答
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));

http://eval.in/14944

于 2013-04-05T12:40:02.517 回答