doulan8054 2015-09-08 21:43
浏览 58
已采纳

循环遍历PHP数组并在Javascript代码中显示值

I have an Array $array and want to create an html5 chart using the values of that array. For that purpose I use chart.js

The code I use looks like this (Unfortunately, I need to output the Javascript via PHP):

$chart = '
<script>
var data = {
    labels: ['."$array[0]".', '."$array[1]".', "..."],
    datasets: [
        {
            label: "My Chart",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};
</script>';
print_r($chart);

That works fine so far, but the array gets updated with time to time and so should the chart. I figured out I would need a loop to do that but am not quite sure how to run the loop in the Javascript code. This doesnt work:

labels: ['.for ($i = 0, $i < count($array), $i++) {echo "$array[$i].','"}.'];
  • 写回答

3条回答 默认 最新

  • dongwen5019 2015-09-08 21:52
    关注

    Create a function to return the array printed. Actually in your code you can remove the echo.

    Please be advised this is a quick hack and shouldn't be used. You should be using some templating function

    function displayMe($ar){
         $res = '';
         for ($i = 0, $i < count($array)-1, $i++){
             $res .= '"'.$array[i].'",';
         }
         return $res . '"'.$array[count($array)-1] . '"';
    }
    
    $chart = '
    <script>
    var data = {
        labels: ['. displayMe($array).'],
        datasets: [
            {
                label: "My Chart",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            }
        ]
    };
    </script>';
    print_r($chart);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀