如何将格式化时间字符串转为数组并赋值给Chart.js的labels参数
Hey there! Let's sort out that issue you're having with converting your concatenated time string into a proper array for Chart.js labels. Here's a step-by-step solution:
1. Split the Processed Time String into Individual Time Entries
Your processed time string is made up of repeating 5-character time values (e.g., 09:00 is 5 characters long). The easiest way to split this into an array is using PHP's str_split() function, which lets you split a string into chunks of a fixed length:
// Your processed time string $processedTime = "09:0001:0012:0011:0010:0001:0000:0023:0022:00"; // Split into 5-character chunks (each chunk is a HH:mm time) $dateArray = str_split($processedTime, 5); // Verify the array (optional, for debugging) var_dump($dateArray);
This will give you exactly the array you need:['09:00','01:00','12:00','11:00','10:00','01:00','00:00','23:00','22:00']
2. Inject the Array into Your Chart.js Configuration
Now you need to pass this array to the labels parameter in your Chart.js code. The cleanest way is to convert the PHP array to a JSON string with json_encode(), which is directly compatible with JavaScript:
<script type="text/javascript"> var ctx = document.getElementById('myChart2').getContext('2d'); var myChart2 = new Chart(ctx, { type: 'line', data: { labels: <?php echo json_encode($dateArray); ?>, // Use the JSON-encoded array here datasets: [{ backgroundColor: 'rgba(232,72,163,0.2)', borderColor: '#e848a3', label: '29 May 2020', data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062], fill: true, pointRadius: 5, pointHoverRadius: 10, showLine: true }] }, options: { responsive: true, maintainAspectRatio: false, title: { display: true, text: 'Total Online Yesterday', position: 'top', fontSize: 15, fontStyle: 'bold' }, legend: { display: false }, elements: { point: { pointStyle: 'circle' } }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'TIME' }, ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'TOTAL ONLINE' } }] }, tooltips:{ callbacks: { title: function(tooltipItem, data) { return '29 May 2020 '+data['labels'][tooltipItem[0]['index']]; }, label: function(tooltipItem, data) { return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+''; }, }, titleFontSize: 15, bodyFontSize: 15, displayColors: false } } }); </script>
Why str_replace Didn't Work
The str_replace function is meant for replacing specific characters or substrings, but your problem required splitting a string into fixed-length chunks—so str_split() is the right tool for the job here.
内容的提问来源于stack exchange,提问作者Alexsandro Siregar

