在CodeIgniter中使用圆环图(Doughnut Chart)展示从数据库的三列中获取的数据,通常涉及到以下几个步骤:
假设我们有一个名为data
的表,包含三列:category
、value
和description
。
$this->load->database();
$query = $this->db->query('SELECT category, value FROM data');
$data = $query->result_array();
$chart_data = [];
foreach ($data as $row) {
$chart_data[] = [
'label' => $row['category'],
'value' => $row['value']
];
}
我们可以使用Chart.js库来生成圆环图。
首先,在application/views
目录下创建一个视图文件doughnut_chart.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Doughnut Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="doughnutChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('doughnutChart').getContext('2d');
var doughnutChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: <?php echo json_encode(array_column($chart_data, 'label')); ?>,
datasets: [{
data: <?php echo json_encode(array_column($chart_data, 'value')); ?>,
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56',
// Add more colors as needed
],
hoverOffset: 4
}]
},
options: {
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Doughnut Chart Example'
}
}
}
});
</script>
</body>
</html>
在控制器中加载视图并传递数据:
public function index() {
$this->load->database();
$query = $this->db->query('SELECT category, value FROM data');
$data = $query->result_array();
$chart_data = [];
foreach ($data as $row) {
$chart_data[] = [
'label' => $row['category'],
'value' => $row['value']
];
}
$this->load->view('doughnut_chart', ['chart_data' => $chart_data]);
}
application/config/database.php
文件。json_encode
将PHP数组转换为JSON格式,以便在前端使用。通过以上步骤,你可以在CodeIgniter中使用圆环图展示从数据库的三列中获取的数据。希望这个答案对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云