简体   繁体   English

如何使用 json_encode 将 PHP 格式化为 javascript 用于图表?

[英]How to use json_encode to format PHP to javascript for Chart?

I would like to convert a PHP array with json_encode to use values in javascript Chart.js我想使用 json_encode 转换 PHP 数组以使用 javascript Chart.js 中的值

What I have is:我所拥有的是:

$dataSets = [ 0 => [
    'type' => 'line',
    'data' => json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK),
    'backgroundColor' => 'transparent',
    'borderColor' => '#007bff',
    'pointBorderColor' => '#007bff',
    'pointBackgroundColor' => '#007bff',
    'fill' => false
  ],

]; ];

With $val_ca_1 = array('2021-02-01' => 10, '2021-02-02' => 14, '2021-02-03' => 8); $val_ca_1 = array('2021-02-01' => 10, '2021-02-02' => 14, '2021-02-03' => 8);

What I do in javascript:我在 javascript 中做了什么:

new Chart($visitorsChart, {
data: {
  labels: ['2021-02-01', '2021-02-02', '2021-02-03'],
  datasets: <?php echo json_encode($dataSets); ?>
},
options: {
  maintainAspectRatio: false,
  tooltips: {
    mode: mode,
    intersect: intersect
  },

But it displays:但它显示:

data: {
  labels: ['2021-02-01', '2021-02-02', '2021-02-03'],
  datasets: [{
     "type": "line",
     "data": "[10,14,8]"
     "backgroundColor": "transparent",
     "borderColor": "#007bff",
     "pointBorderColor": "#007bff",
     "pointBackgroundColor": "#007bff",
     "fill": false
  }]
},

And there is a problem with 'data', it has to be: “数据”有问题,它必须是:

"data": [10,14,8]

(without double quotes) Any idea? (不带双引号)有什么想法吗? Thanks!谢谢!

You're double-encoding some of the data.您正在对一些数据进行双重编码。 Look at this:看这个:

json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK)

That will pre-encode that part of the data as a string inside $dataSets .这会将那部分数据预编码为$dataSets中的字符串。 So it's already JSON.所以它已经是 JSON。 When you come to convert the whole of $dataSets to JSON, it treats it as the simple string it's already been converted to, rather than an array.当您将整个$dataSets转换为 JSON 时,它会将其视为已转换为的简单字符串,而不是数组。

The solution is simple - don't encode different parts of the data separartely.解决方案很简单——不要单独编码数据的不同部分。 Keep it all in PHP variables and then turn all of it into a JSON string right at the last moment, when you actually need to.将其全部保存在 PHP 变量中,然后在您实际需要的最后一刻将其全部转换为 JSON 字符串。

In practical terms, in your code, just change实际上,在您的代码中,只需更改

'data' => json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK)

to

'data' => array_values($val_ca_1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM