我在创建正确的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错了。因为我需要按“房间”分组。当当前行的空间和下一行的房间相等时,checkIn和checkOut日期必须添加到一个房间。一个房间的记录可以超过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": ""
}
}
THX !!!
答案 0 :(得分:0)
你可以尝试这段代码:
$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;
问题是你在房间相同时创建新对象。