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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?