如何将php_数组关联到[{x:key1,y:value1},{x:key2,y:value2},...]?

时间:2019-07-01 21:22:52

标签: php arrays json chart.js

我想在一个图表中显示带有chart.js的两个折线图。由于某些x值不相同(一个数据集中缺少某些x值,而其他数据丢失了),因此我需要两个数据集的数据都采用以下格式:

[{x: "key1", y: value1}, 
{x: "key2", y: value2}, 
{x: "key3", y: value3}, 
... 
{x: "key_n", y: value_n}]

我的出发点是每个数据集的两个php数组(从mysql数据库获取)。第一个数组的json编码输出是:

["2019-06-25","2019-06-26","2019-06-27","2019-06-28","2019-06-29","2019-06-30","2019-07-01"] 

第二个数组的json编码输出是:

[3.304,3.24,3.137,3.232,3.279,3.298,3.307]

Chart.js确实希望使用以下格式:

[{x: "2019-06-25", y: 3.304}, 
{x: "2019-06-26", y: 3.24}, 
{x: "2019-06-27", y: 3.137}, 
{x: "2019-06-28", y: 3.232}, 
{x: "2019-06-29", y: 3.279}, 
{x: "2019-06-30", y: 3.298}, 
{x: "2019-07-01, y: 3.307}]

我已经尝试过这种方式:

$combined = array_combine($leonie_created_at, $weight_leonie);

foreach( $combined as $key=>$val ) {
      $result .= '{' . 'x: ' . $key . ', y: ' . $val . '}';
}

但是json编码的结果是

 "{x: 2019-06-25, y: 3.304}{x: 2019-06-26, y: 3.24}{x: 2019-06-27, y: 3.137}{x: 2019-06-28, y: 3.232}{x: 2019-06-29, y: 3.279}{x: 2019-06-30, y: 3.298}{x: 2019-07-01, y: 3.307}{x: 2019-07-02, y: 3.18}"

有人有主意吗?

1 个答案:

答案 0 :(得分:0)

您可以对foreach使用简单的json_encode循环

$r  = [];
foreach($a1 as $k => $v){
  $r[] = ['x' => $a1[$k], 'y' => $a2[$k]];
}
echo json_encode($r);

https://3v4l.org/1pOhV