我在创建正确的 JSON 时遇到问题。
这是我从MySQL收到的:
ID room startDate stopDate
4 100 2015-02-03 2015-02-11
103 101 2015-02-03 2015-02-04
104 101 2015-02-22 2015-03-08
203 102 2015-01-27 2015-01-29
204 102 2015-02-05 2015-02-10
以及我获取结果的函数:
public static function read() {
$SQL = "****";
$res = Calendar::con()->query($SQL);
$calendar = array();
$period = array();
$previous = '';
while ($row = mysqli_fetch_assoc($res)) {
$calendarr = new Calendar();
$order = new Period();
$current = $row['room'];
$calendarr->room = $row['room'];
$order->checkIn = $row['startDate'];
$order->checkOut = $row['stopDate'];
array_push($period, $order);
$calendarr->period = $period;
if ($current == $previous) {
$period = array();
$calendarr->debug = 'equal';
array_push($calendar, $calendarr);
} else {
array_push($calendar, $calendarr);
$calendarr->debug = 'not equal';
}
$previous = $current;
}
return $calendar;
}
最后我构建JSON(这部分代码是可以的):
{
"data": [
{
"room": "100",
"period": [
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-11"
}
],
"debug": "not equal"
},
{
"room": "101",
"period": [
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-11"
},
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-04"
}
],
"debug": "not equal"
},
{
"room": "101",
"period": [
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-11"
},
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-04"
},
{
"checkIn": "2015-02-22",
"checkOut": "2015-03-08"
}
],
"debug": "equal"
},
{
"room": "102",
"period": [
{
"checkIn": "2015-01-27",
"checkOut": "2015-01-29"
}
],
"debug": "not equal"
},
{
"room": "102",
"period": [
{
"checkIn": "2015-01-27",
"checkOut": "2015-01-29"
},
{
"checkIn": "2015-02-05",
"checkOut": "2015-02-10"
}
],
"debug": "equal"
}
],
"meta": {
"success": true,
"msg": ""
}
}
但是我的JSON是错误的。因为我需要按"房间"分组。当当前行的空间和下一行的空间相等时,必须将入住和退房日期添加到一个房间。一个房间的记录可以超过 2 个。我需要更正 php 读取功能。
更新:
正确答案后,我收到正确的 JSON:
我的SQL是:
$SQL = "SELECT * FROM Orders WHERE (room = 100 OR room = 101 OR room = 102) AND ((startDate BETWEEN CURDATE() AND (DATE_SUB(CURDATE(), INTERVAL -1 MONTH))) OR (stopDate BETWEEN CURDATE() AND (DATE_SUB(CURDATE(), INTERVAL -1 MONTH)))) order BY room";
和正确的 JSON:
{
"data": [
{
"room": "100",
"period": [
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-11"
}
]
},
{
"room": "101",
"period": [
{
"checkIn": "2015-02-03",
"checkOut": "2015-02-04"
},
{
"checkIn": "2015-02-22",
"checkOut": "2015-03-08"
}
]
},
{
"room": "102",
"period": [
{
"checkIn": "2015-01-27",
"checkOut": "2015-01-29"
},
{
"checkIn": "2015-02-05",
"checkOut": "2015-02-10"
}
]
}
],
"meta": {
"success": true,
"msg": ""
}
}
感谢!!!
你能试试这段代码吗:
$previous = '';
while ($row = mysqli_fetch_assoc($res)) {
$current = $row['room'];
if ($current != $previous) {
$calendarr = new Calendar();
$calendarr->room = $row['room'];
$calendarr->period = array();
$calendar[] = $calendarr;
$previous = $current;
}
$order = new Period();
$order->checkIn = $row['startDate'];
$order->checkOut = $row['stopDate'];
$calendarr->period[] = $order;
}
return $calendar;
问题是您在房间相同时创建新对象。