我正在建立一个网站,用户可以在这里预约。
我目前正在为该项目构建一个javascript应用程序,用户可以在其中从日历中选择日期并查看可用的约会。当我制作日历时,我需要根据可用的约会为日期上色(例如,如果有,则为绿色)。
为了做到这一点,我需要迭代一个包含所有可用保留的javascript数组。目前它看起来像这样:
[对象,对象,对象…]
其中,对象是包含约会信息的javascript对象。以下是为JSON:提供服务的php服务
<?php
require_once('../include/dbconnect.php');
$sql = "SELECT appointment.example,...
person.example,...
FROM appointment, person
WHERE appointment.reserved=0";
$stmt = $db->prepare($sql);
$stmt->execute();
$array = array();
while($row = $stmt->fetchObject()){
array_push($array, $row);
}
echo json_encode($array);
?>
因此,这最终引出了我们的问题。
为了更容易地扫描javascript数组,我需要一个数组/对象,其中包括按日期排列/排序的约会。然后,当我创建一个表示日期的元素时,我可以检查对象是否有匹配的数据。数据如下:
{
15.09.2012 : Object,
16.09.2012 : Object{
appointment1 : Object,
appointment2 : Object
}
}
在数据库中,约会有一个属性"date",目前是一个类似"16.09.2012"的字符串。我是否也应该将其更改为unix时间戳?
我应该如何更改PHP服务以输出一个JSON对象,其中包括在日期下提交的约会?
一个可能的解决方案是在php:中使用关联数组
$assoc = array("key" => "value");
当你获取数据库记录时,你可以这样做:
$array = array();
while($row = $stmt->fetchObject()){
$array[$row -> date] = $row;
}
echo json_encode($array);
对于排序,可以使用ksort
(http://php.net/manual/en/function.ksort.php)php函数,按键对数组进行排序。
现在您将拥有一个Javascript对象,而不是Javascript数组。现在,您可以使用for来迭代对象。。在javascript循环中(如何循环通过以对象为成员的纯javascript对象?)
您可以按如下方式进行尝试:
$sql = "SELECT appointment.example,...
person.example,...
FROM appointment, person
WHERE appointment.reserved=0 ORDER BY appointment.date_field ASC";
$stmt = $db->prepare($sql);
$stmt->execute();
$array = array();
while($row = $stmt->fetchObject()){
$array[$row->date_field][]=$row;
array_push($array, $row);
}
echo json_encode($array);
?>
您不需要构造一个由日期键组成的对象。相反:
-
将日期包括在当前结构中,并按日期对数组进行排序:
<?php require_once('../include/dbconnect.php'); $stmt = $db->query(' SELECT DATE(appointment.datetime) AS date, appointment.datetime, appointment.reserved, appointment.example, -- do you really want to send sensitive person.example -- data about appointments to the browser? FROM appointment JOIN person ON ... WHERE appointment.reserved = 0 -- should this be = 1? ORDER BY appointment.datetime '); echo json_encode($stmt->fetchAll(PDO::FETCH_OBJ)); ?>
-
然后在通过阵列时跳过匹配的天数:
// loop over all dates displayed in calendar for ( currentDate = startDate, i = 0; currentDate <= endDate; currentDate.setDate(currentDate.getDate() + 1) ){ // determine whether the current date is booked // and advance pointer to next date in array for ( booked = false; i < arr.length && arr[i].date == currentDate; ++i ) booked |= arr[i].reserved; // or just `booked = true` if query // returned only booked appointments // apply appropriate CSS to currentDate // ... }
您甚至可以考虑通过首先只返回预订日期的JSON数组来减少客户端开销(在这种情况下,上面的内部循环可以用简单的if
语句代替):
SELECT DISTINCT DATE(appointment.datetime) AS date
FROM appointment JOIN person ON ...
WHERE appointment.reserved = 0 -- should this be = 1?
ORDER BY date
然后,一旦用户选择了一个日期,就可以进一步查询该日期的预订:
SELECT appointment.datetime
FROM appointment JOIN person ON ...
WHERE appointment.reserved = 0 -- should this be = 1?
AND DATE(appointment.datetime) = ?
ORDER BY appointment.datetime