如何从codeigniter中的模型生成json格式到Highchart
Posted
技术标签:
【中文标题】如何从codeigniter中的模型生成json格式到Highchart【英文标题】:How To generate json format from model in codeigniter to Highchart 【发布时间】:2021-01-17 18:50:42 【问题描述】:我有数据库
[![在此处输入图片描述][1]][1]
[1]:https://i.stack.imgur.com/yAteS.jpg;
如何显示 json 数据格式,例如像这样的 highcharts 下钻示例
name: '2010',
data: [
name: 'Republican',
y: 5,
drilldown: 'republican-2010'
,
name: 'Democrats',
y: 2,
drilldown: 'democrats-2010'
,
name: 'Other',
y: 4,
drilldown: 'other-2010'
]
,
name: '2014',
data: [
name: 'Republican',
y: 4,
drilldown: 'republican-2014'
,
name: 'Democrats',
y: 4,
drilldown: 'democrats-2014'
,
name: 'Other',
y: 4,
drilldown: 'other-2014'
]
【问题讨论】:
嗨@Feri,您也可以稍后在前端通过JS转换您的JSON。 【参考方案1】:你需要json_encode
根据模型结果,通过循环遍历每条记录,您需要创建如图所示的结构化数据。
# create an array structure like the one below
$chart_data = array(
array(
'name'=> '2010',
'data'=> array(
array(
'name'=> 'Republican',
'y'=> 5,
'drilldown'=> 'republican-2010'
),
array(
'name'=> 'Democrats',
'y'=> 2,
'drilldown'=> 'democrats-2010'
),
array(
'name'=> 'Other',
'y'=> 4,
'drilldown'=> 'other-2010'
),
...
)
),
...
)
;
$chart_data_json_string = json_encode($chart_data);
// $chart_data_json_string would contain a string that can be parsed into JSON from the front end
// $chart_data_json_string = ["name":"2010","data":["name":"Republican","y":5,"drilldown":"republican-2010","name":"Democrats","y":2,"drilldown":"democrats-2010","name":"Other","y":4,"drilldown":"other-2010"]]
使用JSON.parse(json_string)将字符串解析为json,然后可以使用 作者:Highchart
let high_chart_data_str = '<?php $chart_data_json_string ?>';
let high_chart_data = JSON.parse(high_chart_data_str);
【讨论】:
【参考方案2】:试试这个
SELECT JSON_ARRAYAGG(JSON_OBJECT('id', id, 'nama', nama, 'tahun', tahun, 'zone', zone, 'nilai', nilai)) from TableA;
【讨论】:
以上是关于如何从codeigniter中的模型生成json格式到Highchart的主要内容,如果未能解决你的问题,请参考以下文章
如何将结果从模型传递到 CodeIgniter 中的控制器?