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 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形