动态Morris Line字符串转换ERROR

时间:2017-09-15 18:29:32

标签: php mysql morris.js

我正在尝试用来自mysql的数据使用php进行Morris Line Chart ..但是当我调试时,我在控制台中得到Array to string conversion错误。以下是我的代码

       <?php

            try { $stmt = $db->prepare(" SELECT register_date FROM members  ");
                    $stmt->execute();
                }
             catch(PDOException $e) {
                    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
                    }


                $chart_data = array(); // define array

                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $signup = date('F d Y ', strtotime($row["register_date"]));

                    $chart_data .= "{ date: '" .$signup. "' },";

                    }

        ?>

        <script type="application/javascript">

            Morris.Line({
                    element: 'signups',  // div id
                    data: [<?php echo $chart_data; ?>],
                    xkey: 'date',
                    ykeys: 'date',
                    lables: 'sigups',
                    hidehover: 'auto' 


                });

        </script>

1 个答案:

答案 0 :(得分:0)

$chart_data包含无效的json

请不要发明轮子并使用json_encode

$chart_data = array(); // define array
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $signup = date('F d Y ', strtotime($row["register_date"]));
    $chart_data[] = ['date' => $signup];
}

JS-部分:

Morris.Line({
    element: 'signups',  // div id
    data: <?php echo json_encode($chart_data); ?>,
    xkey: 'date',
    ykeys: 'date',
    lables: 'sigups',
    hidehover: 'auto' 
});