PHP - 正确分组数据并获取数据之间的数据

我有一张桌子要预订:


id         room_id        start          end

1          1              2019-10-04     2019-10-14

2          1              2019-10-13     2019-10-22

3          1              2019-12-16     2019-12-25

4          1              2019-11-30     2019-12-18

房间表:


id         name        type

1          002         1-A

2          005         3-B

所以我只想要一个房间类型的样本,1-A我想将预订分组foreach到这个输出:


start_date => 2019-10-04      AND    end_date => 2019-10-22

start_date => 2019-11-30      AND    end_date => 2019-12-25

应该有2组。


我试过用这个


$new = array();

foreach($bookingArr as $booking) {

   $new[$booking->room_id][$booking->start][] = $booking;

}

但我没有得到我想要的输出。


慕田峪4524236
浏览 108回答 1
1回答

慕婉清6462132

首先,您需要按开始日期排序结果。在您需要实现日期起止期间的交集之后。假设它已经完成,代码可能与此类似:<?php$bookingData = [&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'room_type' => '1-A',&nbsp; &nbsp; &nbsp; &nbsp; 'start'&nbsp; &nbsp; &nbsp;=> '2019-10-04',&nbsp; &nbsp; &nbsp; &nbsp; 'end'&nbsp; &nbsp; &nbsp; &nbsp;=> '2019-10-14',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'room_type' => '1-A',&nbsp; &nbsp; &nbsp; &nbsp; 'start'&nbsp; &nbsp; &nbsp;=> '2019-10-13',&nbsp; &nbsp; &nbsp; &nbsp; 'end'&nbsp; &nbsp; &nbsp; &nbsp;=> '2019-10-22',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'room_type' => '1-A',&nbsp; &nbsp; &nbsp; &nbsp; 'start'&nbsp; &nbsp; &nbsp;=> '2019-11-30',&nbsp; &nbsp; &nbsp; &nbsp; 'end'&nbsp; &nbsp; &nbsp; &nbsp;=> '2019-12-18',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'room_type' => '1-A',&nbsp; &nbsp; &nbsp; &nbsp; 'start'&nbsp; &nbsp; &nbsp;=> '2019-12-16',&nbsp; &nbsp; &nbsp; &nbsp; 'end'&nbsp; &nbsp; &nbsp; &nbsp;=> '2019-12-25',&nbsp; &nbsp; ],];$output = [];$k = -1;foreach ($bookingData as $data) {&nbsp; &nbsp; $curr = $output[$k] ?? null;&nbsp; &nbsp; if ($curr !== null &&&nbsp; &nbsp; &nbsp; &nbsp; $data['start'] >= $curr['start'] &&&nbsp; &nbsp; &nbsp; &nbsp; $data['start'] <= $curr['end'] &&&nbsp; &nbsp; &nbsp; &nbsp; $data['end'] > $curr['end']) {&nbsp; &nbsp; &nbsp; &nbsp; $output[$k]['end'] = $data['end'];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $output[] = $data;&nbsp; &nbsp; &nbsp; &nbsp; $k++;&nbsp; &nbsp; }}foreach ($output as $item) {&nbsp; &nbsp; echo sprintf("start_date => %s AND end_date => %s\r\n", $item['start'], $item['end']);}
打开App,查看更多内容
随时随地看视频慕课网APP