ds34222 2017-07-04 03:39
浏览 82
已采纳

如何在Javascript数组中存储MySQL日期?

I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.

Let say,

My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.

How can I store in Javascript after I converted them into json by

<?php
    $sql = "SELECT public_holiday.holiday_date 
            FROM public_holiday";
    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
         $result_array[] = $row;
    }

    $json_array = json_encode($result_array);

    echo $json_array;
  ?>

?

I have tried to store them into a javascript date array like

var holidays = [<?php //sample array for example 
        $loop_one = true;
        foreach ($result_array as $date) 
        {
            if ($loop_one) 
            {
                echo "'new Date(\'$date\')'";
                $loop_one=false;
            } 
            else 
            {
                echo ", 'new Date(\'$date\')'";
            }
        }
?>];

but all of these are invalid.

I need your help, much appreciated.

  • 写回答

3条回答 默认 最新

  • dongyin8009 2017-07-04 07:07
    关注

    To get a javaScript date object array you need to change your script code only no need to change the PHP code.
    You can use JSON.parse and forEach loop.

    Try like this

    <script>
        var holidays = '<?php  echo $json_array;?>';
        holidays=JSON.parse(holidays);
        var holidayArray=[];
        holidays.forEach(function (key) {
            holidayArray.push(new Date(key));
        });
        console.log(holidays);
        console.log(holidayArray);
    </script>
    

    It will produce an out put as

    enter image description here

    I thing it will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!