mysql php 将开始日期和结束日期与价格分组

mysql php grouping start date and end date with price

我有一个 mysql table 存储租赁系统的每日价格。 Table 有 ID、property_id、日期和价格

id 1 | propertyid 1 | date 2015-05-01 | price 300
id 2 | propertyid 1 | date 2015-05-02 | price 300
id 3 | propertyid 1 | date 2015-05-03 | price 300
id 4 | propertyid 1 | date 2015-05-04 | price 300
id 5 | propertyid 1 | date 2015-05-05 | price 500
id 6 | propertyid 1 | date 2015-05-06 | price 500
id 7 | propertyid 1 | date 2015-05-07 | price 700
id 6 | propertyid 1 | date 2015-05-08 | price 900
id 7 | propertyid 1 | date 2015-05-09 | price 900

我得到的结果是

( SELECT * from price WHERE property_id = 1 ORDER BY date ASC)

问题是,我需要将相同日期的价格与开始日期和结束日期分组,但我不知道从哪里开始以及如何开始。结果应该像

startdate = 2015-05-01 enddate = 2015-05-05 price = 300
startdate = 2015-05-05 enddate = 2015-05-07 price = 500
startdate = 2015-05-07 enddate = 2015-05-08 price = 700
startdate = 2015-05-08 enddate = 2015-05-10 price = 900

有了这个,我可以获得 1 年的所有价格,但如果日期数组中的价格相同,我可以将它们分组。我得到了 foreach 中的所有值,但不知道如何对它们进行分组。

谢谢。

这是 php 中的一种方法。

首先,将所有返回的数据库行保存到一个数组中-

while($row = fetchRow()){
    $rows[] = $row;
}

其次,创建一个数组来保存组、一个计数器变量和最后一个行键。

$ranges=array();
$x=0;
$last=count($rows)-1;

第三,通过执行以下操作遍历每个返回的行 - 设置范围 startdate/price。如果是最后一行,则设置结束日期;否则,如果下一行价格不相同,则设置结束日期并增加计数器(对于单个日期范围);否则,如果价格与当前范围价格不同,则设置结束日期并增加计数器。

foreach($rows as $key=>$row){
    //if range startdate not set, create the range startdate and price
    if(!isset($ranges[$x]['startdate'])){
        $ranges[$x] = array('startdate'=>$row['startdate'], 'price'=>$row['price']);
    }

    //if the last row set the enddate
    if($key==$last){
        $ranges[$x]['enddate'] = $row['startdate'];
    }
    //if the next price is not the same, set the enddate and increase the counter (single date range)
    else if($row['price']!=$rows[$key+1]['price'] ){
        $ranges[$x]['enddate'] = $row['startdate'];
        $x++;
    }
    //if the price is not the same as the current range price, set the enddate and increase the counter
    else if($row['price']!=$ranges[$x]['price'] ){
        $ranges[$x]['enddate'] = $rows[$key-1]['startdate'];
        $x++;
    }
}

最后,遍历范围并打印值

foreach($ranges as $range){
    echo "startdate = {$range['startdate']} enddate = {$range['enddate']} price = {$range['price']}<br />";
}