根据基于数据库值的可用天数更新datepicker

时间:2018-03-26 15:42:03

标签: php jquery html arrays

我目前正在尝试根据从mysql数据库中获取并存储在php数组中的值来禁用jquery datepicker上的某些日期。我无法将php数组转换为jquery,然后读取值以禁用未被选择为用户可用的日期。任何人都可以指导我完成创建此功能所需的操作。在将php数组编码为json

之后,我在这个过程中有点迷失了
 $daysavailquery = "SELECT Monday, Tuesday, Wednesday, Thursday, Friday, 
 Saturday, Sunday FROM miiLearning_tutorAvail WHERE id = 
 $id";

$daysavailresult = mysqli_query($conn, $daysavailquery);

$daysavailarray = mysqli_fetch_array($daysavailresult);

//Convert days avail to json
$DaysAvailJSON = json_encode($daysavailarray);
echo $DaysAvailJSON;

<script>
        $( function() {


            $( "#datepicker" ).datepicker({
                dateFormat: "yy-mm-dd"
                var daysAvailArray = <?php echo json_encode($daysavailarray) ?>
                beforeShowDay: function(date) {

                var day = date.getDay();
                console.log(day);

                if (day == 0 && daysAvailArray[0]==1)
                  return [true];
                if (day == 1 && daysAvailArray[0]==1)
                  return [true];
                if (day == 2 && daysAvailArray[0]==1)
                  return [true];
                if (day == 3 && daysAvailArray[0]==1)
                  return [true];
                if (day == 4 && daysAvailArray[0]==1)
                  return [true];
                if (day == 5 && daysAvailArray[0]==1)
                  return [true];
                if (day == 6 && daysAvailArray[0]==1)
                  return [true];

                return [false];
              }
            });
        } );
    </script>

<div class="form-group">
     <label for="datepicker">Pick a date</label>
     <input type="text" date-date- format="yy-mm-dd" name="datepicker" 
id="datepicker" class="form-control" required>
</div>

1 个答案:

答案 0 :(得分:0)

我将假设该表包含每天的真值或假值。

$daysavailarray = mysqli_fetch_array($daysavailresult);
// should be have associate array
//[ 'monday' => '1', 'Sunday' => '0']
// we don't need the day name so we will use MYSQLI_NUM to have it as numerical index [ 0 => '1' , 1 => '0' ]
$daysavailarray = mysqli_fetch_array($daysavailresult, MYSQLI_NUM);

现在想将php数组转换为javascript数组json_encode将完成工作

var daysAvailArray = <?php echo json_encode($daysavailarray) ?>;

因为我们将日作为索引,所以更容易看出它是否为假

var day = date.getDay();
console.log(day);
return daysAvailArray[day-1] ? [true] : [false];

完整的JavaScript代码

<script>
    $( function() {
        var daysAvailArray = <?php echo json_encode($daysavailarray) ?>;
        $( "#datepicker" ).datepicker({
            dateFormat: "yy-mm-dd",
            beforeShowDay: function(date) {
                var day = date.getDay();
                return (daysAvailArray[day-1] == '1') ? [true] : [false];                           
            }
        });
    } );
</script>