合并相同的数组值

时间:2017-02-17 01:34:46

标签: php arrays

我有一个这样的数组:

$storeArray = array('Monday' => '08:30 - 16:30',
                    'Tuesday' => '08:30 - 15:30',
                    'Wednesday' => 08:30 - 16:30',
                    'Thursday' => 08:30 - 16:30',
                    'Friday' => 14:30 - 13:30',
                    'Saturday' => 14:30 - 13:30',
                    'Sunday' => 10:00 - 15:30'
              );

现在我想合并所有相同的数组值并按如下方式打印数组:

Monday - Wednesday - Thursday : 08:30 - 16:30
Tuesday : 08:30 - 15:30
Friday - Saturday: 14:30 - 13:30
Sunday: 10:00 - 15:30

1 个答案:

答案 0 :(得分:4)

这个想法只是分组和翻转它。通过对值进行分组重新分配值,在它们全部分组后(意味着所有时间),翻转分组的数组。

点子:

// group
$datetime = array();
foreach ($storeArray as $day => $time) {
    $datetime[$time][] = $day;
}
// and
// implode flip
$datetime = array_flip(array_map(function($e){
    return implode(' - ', $e);
}, $datetime));

这应该会产生这样的结果:

Array
(
    [Monday - Wednesday - Thursday] => 08:30 - 16:30
    [Tuesday] => 08:30 - 15:30
    [Friday - Saturday] => 14:30 - 13:30
    [Sunday] => 10:00 - 15:30
)

现在你可以做你想做的事。

另一个版本,结果相同:

// container, total count, counter
$datetime = array(); $len = count($storeArray); $i = 0;
foreach ($storeArray as $day => $time) {
    if (!isset($datetime[$time])) {
        $datetime[$time] = ''; // initialize
    }
    $datetime[$time] .= $day . ' - '; // concatenate dash
    if ($i == ($len - 1)) { // at the end of the loop, make cosmetic changes, remove extra dash
        // remove each extra dash, then flip
        $datetime = array_flip(array_map(function($e){ return rtrim($e, ' - '); }, $datetime));
    }
    $i++; // counter
}