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条)

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法