用PHP排序开放时间

时间:2016-11-08 10:44:26

标签: php arrays sorting

我有一个开放时间如下所示的阵列:

array:7 [
  "mon" => array [
    "open" => null
    "close" => null
  ]
  "tue" => array [
    "open" => null
    "close" => null
  ]
  "wed" => array [
    "open" => "09:00"
    "close" => "20:00"
  ]
  "thu" => array [
    "open" => null
    "close" => null
  ]
  "fri" => array [
    "open" => "14:00"
    "close" => "17:00"
  ]
  "sat" => array [
    "open" => "12:00"
    "close" => "15:00"
  ]
  "sun" => array [
    "open" => "12:00"
    "close" => "15:00"
  ]
]

我想创建一个这样的结构:

array [
  array [
        "mon" => array [
          "open" => null
          "close" => null
        ]
        "tue" => array [
            "open" => null
            "close" => null
        ]
    ]
    array [
        "wed" => array [
            "open" => "09:00"
            "close" => "20:00"
        ]
    ]
    array [
        "thu" => array [
            "open" => null
            "close" => null
        ]
    ]
    array [
        "fri" => array [
            "open" => "14:00"
            "close" => "17:00"
        ]
    ]
    array [
        "sat" => array [
            "open" => "12:00"
            "close" => "15:00"
        ]
        "sun" => array [
            "open" => "12:00"
            "close" => "15:00"
        ]
    ]
]

只要日期连续,具有相同开放时间的日期就会组合在一起。否则,一天应该自行结束。

我一直在用PHP实现这个目标,这是我到目前为止所做的。

$hours = []; 
$previousDay = null;

foreach ($days as $key => $day)
{   
    if ($day === $previousDay)
    {
        $hours[] = array($key => $day); 
    }
    else 
    {
        $hours[] = array($key => $day); 
    }

    $previousDay = $day; 
}  

我坚持如何在一个阵列中将相同开放时间的日子分组。

1 个答案:

答案 0 :(得分:1)

下面怎么样?

$result = array();
$previous = null;
$idx = -1;
foreach ($days as $key => $day){
    if($day !== $previous){
        $idx++;
    }
    $result[$idx][$key] = $day;
    $previous = $day;
}