如何在php中检查数组中的相同值

时间:2013-04-05 11:56:05

标签: php arrays

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

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

)

任何人都能帮助我吗?

5 个答案:

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

Here's a working example

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

http://eval.in/14944