将字符串转换为高图js的数组

时间:2017-10-09 20:49:07

标签: javascript php highcharts

我的代码PHP生成一个字符串变量

<?php
foreach($rows as $row){

    $result .= "['" .$row["Name"]."'," .$row['Value']. "] , ";
}

$result = rtrim($result, ' , ');

//echo $result returns: ['FirstName1 LastName1',10] , ['FirstName2 LastName2',12] , ['FirstName3 LastName3 ',40]

?>

在js中如何转换&#39;名称&#39;变量为数据的函数变量:&#39; ?

<script>
var name = "<?php echo $result; ?>";

Highcharts.chart('container', {
...

data: [
    ['Shanghai', 23.7],
    ['Lagos', 16.1],
    ['Istanbul', 14.2]
  ];

...
});
</script>

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要将$result包装在数组中:

$result = "[$result]";

但你真的应该像这样使用json_encode

$resultArr = [];
foreach ($rows as $row) {
    $resultArr[] = [$row['Name'], $row['Value']];
}
$result = json_encode($resultArr);