php – 如何合并具有相同数据的连续subArrays?

前端之家收集整理的这篇文章主要介绍了php – 如何合并具有相同数据的连续subArrays?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个数组:
$opening_hours = array(
  'Monday' => array('09:00','17:00'),'Tuesday' => array('09:00','Wednesday' => array('08:00','13:00'),'Thursday' => array('09:00','Friday' => array('09:00','Saturday' => array('10:00','16:00'),'Sunday' => array('Closed'),);

我需要以某种方式将这些开放时间合并到数组中,这应该是这样的:

$merged_opening_hours = array(
  'Monday - Tuesday' => array('09:00','Thursday - Friday' => array('09:00','16:00');
  'Sunday' => array('Closed'),);

有任何想法吗?

这应该适合你:

所以基本上你只需循环遍历整个数组并检查下一个元素是否仍然设置并且当前数组与下一个元素相同(这意味着它们具有相同的小时数).如果是,则执行此操作,直到while循环返回false.这是什么代码

$DayAmountOfConsecutiveSameHours = 1;
while(isset($arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]) && 
     ($opening_hours[$arrayKeys[$dayCount]] === $opening_hours[$arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]]))
    $DayAmountOfConsecutiveSameHours++;

然后,如果您有多个条目,则创建从一个到另一天的范围.这是什么代码

if($DayAmountOfConsecutiveSameHours > 1)
    $result[$arrayKeys[$dayCount] . " - " . $arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours-1)]] = $opening_hours[$arrayKeys[$dayCount]];

如果您只有相同时间的1天,则只需将其添加到结果数组中.这是什么代码

else
    $result[$arrayKeys[$dayCount]] = $opening_hours[$arrayKeys[$dayCount]];

根据你在同一时间内跳过下一个数组元素的天数.这是什么代码

$dayCount += ($DayAmountOfConsecutiveSameHours - 1);

完整代码

<?PHP

    $opening_hours = [
            "Monday" => ["09:00","17:00"],"Tuesday" => ["09:00","Wednesday" => ["08:00","13:00"],"Thursday" => ["09:00","Friday" => ["09:00","Saturday" => ["10:00","16:00"],"Sunday" => ["Closed"],];


    $amountOfDays = count($opening_hours);
    $arrayKeys = array_keys($opening_hours);

    for($dayCount = 0; $dayCount < $amountOfDays; $dayCount++) {
        $DayAmountOfConsecutiveSameHours = 1;
        while(isset($arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]) && ($opening_hours[$arrayKeys[$dayCount]] === $opening_hours[$arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]]))
            $DayAmountOfConsecutiveSameHours++;

        if($DayAmountOfConsecutiveSameHours > 1)
            $result[$arrayKeys[$dayCount] . " - " . $arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours-1)]] = $opening_hours[$arrayKeys[$dayCount]];
        else
            $result[$arrayKeys[$dayCount]] = $opening_hours[$arrayKeys[$dayCount]];

        $dayCount += ($DayAmountOfConsecutiveSameHours - 1);
    }

    print_r($result);

?>

输出

Array
(
    [Monday - Tuesday] => Array
        (
            [0] => 09:00
            [1] => 17:00
        )

    [Wednesday] => Array
        (
            [0] => 08:00
            [1] => 13:00
        )

    [Thursday - Friday] => Array
        (
            [0] => 09:00
            [1] => 17:00
        )

    [Saturday] => Array
        (
            [0] => 10:00
            [1] => 16:00
        )

    [Sunday] => Array
        (
            [0] => Closed
        )

)

Demo

原文链接:https://www.f2er.com/php/137438.html

猜你在找的PHP相关文章