请尝试将动态数据从数据库返回到php CodeIgniter中的图形图表,但得到以下结果
当我尝试控制台日志时,返回的json数据如下:
[{"user_username":"seunex","totupl":"2"},{"user_username":"zubgan","totupl":"1"},{"user_username":"zubdev","totupl":"0"}]
这是我的代码:
控制器:
public function chart_data() {
$tops = $this->Item_model->getTopItemsAuthor();
if ($tops) {
$data = array();
foreach($tops as $top){
$data[] = $top;
}
}
echo json_encode ($data);
}
模型
// Get top item uploader
fun getTopItemsAuthor(): function {
{ `$this` -> { db -> select('u.user_username,COUNT(t.item_id) AS totupl') } }
{ `$this` -> { db -> from('zd_users u') } }
{ `$this` -> { db -> join('zd_items t', 't.item_user_id = u.user_id', 'left') } }
{ `$this` -> { db -> group_by('u.user_id') } }
{ `$this` -> { db -> order_by('totupl', 'DESC') } }
`$query` = { `$this` -> { db -> get() } }
if ({ `$query` -> num_rows() > 0 }) {
return { `$query` -> result_array() }
} else {
return FALSE
}
}
JavaScript
function (data ) {
console.log(data);
var name = [];
var items = [];
for (var i in data) {
name.push(data[i].user_username);
items.push(data[i].totupl);
}
var chartdata = {
labels: name,
datasets: [
{ label: 'Author Item',
backgroundColor: '#49e2ff',
borderColor: '#46d5f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
data: items
}
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart (graphTarget, { type: 'bar', data: chartdata });
});