You have data, you want to chart it in highcharts. Good choice, now what’s the best way to do that?

I like to create a json generating file that gets called by a javascript function. Here’s an example.

$get_var = filter_input(INPUT_GET,'var');
$get_period = filter_input(INPUT_GET,'period');
$get_group = filter_input(INPUT_GET,'group');
$get_model = filter_input(INPUT_GET,'model');
$get_toy = filter_input(INPUT_GET,'toy');
$get_rcp = filter_input(INPUT_GET,'rcp');
$get_tract = filter_input(INPUT_GET,'tract');

$query = mysqli_query($con,"SELECT model_percentiles as model,".$get_var." as value FROM 
projected where geoid_short=".$get_tract." and rcp='".$get_rcp."' and group='".$get_group."' and
 time_of_year='".$get_toy."' order by model asc")
or die(mysqli_error($con));

while ($row = mysqli_fetch_assoc($main_query))
{
    $response[$row['model']] .= $row['value'].',';
}

$final_response = [];

foreach ($response as $key => $value){
    // remove the trailing comma
    $value = rtrim($value, ',');
    // convert trimmed value into array
    $newvalue = explode(',',$value);
    // ensure we're not getting back strings.
    array_walk( $newvalue, 'intval' );
    // format the array to be highcharts-ready.
    $final_response[$key]['name'] = $key;
    $final_response[$key]['data'] = $newvalue;
}
// trim the parent keys to make the return highcharts ready
$final_response = array_values($final_response);
        
echo json_encode($final_response,JSON_NUMERIC_CHECK);

In our example, this returns the following

[{
	"name": 5,
	"data": [65.03, 67.27, 66.77, 66.15, 65.44, 65.54, 65.59, 65.13]
}, {
	"name": 33,
	"data": [65.15, 65.01, 65.59, 64.96, 65.81, 65.91, 64.77, 65.57]
}, {
	"name": 50,
	"data": [65.12, 65.22, 65.62, 66.82, 65.67, 65.41, 66.44, 65.55]
}, {
	"name": 66,
	"data": [66.29, 65.63, 65.94, 64.74, 65.46, 65.07, 66.02, 65.27]
}, {
	"name": 95,
	"data": [65.57, 65.21, 66.91, 65.75, 65.08, 65.75, 65.4, 66.99]
}]

Now you can have a function to generate the chart data, I threw in a coloring function so you can easily add custom colors. 

function lineColor(n) {
    return n === 5 ? '#800026' :
        n === 4 ? '#BD0026' :
            n === 3 ? '#E31A1C' :
                n === 2 ? '#FC4E2A' :
                    n === 1 ? '#FD8D3C' :
                        '#000000';
}

function getChartData(filterOptions) {
    var points = [];
    $.ajax({
        url: '//domain.com/api.php?var=' + var,
        async: false,
        dataType: 'json',
        success: function (data) {
            points = data;
        },
        cache: true
    });
    var i;
    for (i = 0; i < points.length; ++i) {
        points[i]['color'] = lineColor(i+1);
    }
    return points;
}