javascript - 将字符串转换为数组以用于 highcharts js

标签 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 中,如何将 'name' 变量转换为 'data:' 的函数变量?

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

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

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

...
});
</script>

谢谢!

最佳答案

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

$result = "[$result]";

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

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

关于javascript - 将字符串转换为数组以用于 highcharts js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46654737/

相关文章:

javascript - 防止使用turbolinks和highcharts执行之前的JavaScript//LazyHighCharts

javascript - 单击时检索 jQuery 数组元素的值

javascript - 如何将嵌套数组转换为逗号分隔的字符串

php - 从 MYSQL 中的每组中选择 N 行

php - 如何在mysql中存储配置变量?

php - 使用 PHP 返回行的问题

javascript - jquery ajax 异步没有相应地工作

javascript - Google map 无法使用 jquery 加载

javascript - Highcharts : How to flag the local maxima on a dynamic graph drawn using HighChart

javascript - Extjs 与 HighCharts