You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置PHP生成的Chart.js折线图:指定轴与数据集

Fixing Your Chart.js Axes and Dataset Setup

Let's adjust your code to match the desired chart configuration where:

  • X-axis uses the rates (40, 60, 80)
  • Each dataset is a day (Monday, Tuesday, Wednesday)
  • Y-axis displays the calculated net profits (800, 1200, 1600)

Key Issues in the Original Code

  1. The $profit array was being overwritten in each inner loop iteration, so each day only kept the last rate's profit value.
  2. The chart labels were set to days instead of rates, swapping the X-axis with the dataset names.

Corrected Code

$days = ["Monday","Tuesday","Wednesday"]; 
$rates = [40,60,80]; 
$profit = []; 

// Build the profit array correctly with all rate-profit pairs per day
foreach($days as $dayName) {
    $profit[$dayName] = []; // Initialize empty array for the day
    foreach($rates as $rate) {
        $netProfit = $rate * 20;
        $profit[$dayName][$rate] = $netProfit;
    }
}

$usersChart = new UserChart; 
// Set X-axis labels to the rates (matches desired X-axis)
$usersChart->labels($rates); 

// Create a dataset for each day, using profits in rate order
foreach($profit as $dayName => $rateProfits) {
    $data = [];
    // Ensure data points match the order of X-axis labels
    foreach($rates as $rate) {
        $data[] = $rateProfits[$rate];
    }
    $usersChart->dataset($dayName, 'line', collect($data));
}

What This Does

  1. Proper Profit Array Construction: We initialize an empty array for each day first, then add every rate-profit pair to it, resulting in the exact array structure you specified.
  2. X-Axis Labels: The chart's labels are now set to $rates, making the X-axis show 40, 60, 80.
  3. Dataset Order: For each day, we explicitly pull profit values in the order of the rates to ensure they align correctly with the X-axis labels.

This will generate a line chart where each line represents a day, plotting the net profits against the corresponding rates on the X-axis.

内容的提问来源于stack exchange,提问作者H M Sadman Haque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:22:46