Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining two arrays and send them to Highcharts

I am trying to adapt the code obtained on the web for my use. I have a lot of experience in C, C++ and Python, but almost none in PHP, so I do not know where to start, because I don’t fully understand code and PHP concepts.

So the idea is that the program reads data from the SQL table, etime is epoch time (integer) and value are float values (strings). Then those data are plotted using Highcharts, where in the original code etime is category.

PHP part:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$etime = json_encode(array_reverse(array_column($sensor_data, 'etime')), JSON_NUMERIC_CHECK);
$value = json_encode(array_reverse(array_column($sensor_data, 'value')), JSON_NUMERIC_CHECK);

var etime = <?php echo $etime; ?>;
var value = <?php echo $value; ?>;

Javascript (?) part:

var chartT = new Highcharts.Chart({
  series: [{
    data: value
  }],
  xAxis: { 
    categories: etime
  }
});

I would like to adapt this code so that etime is datetime instead of category. As far as I understand from the web, I should combine arrays $etime and $value into an array of pairs [$etime, $value] and change categories: etime to type: 'datetime'. However, I do not know how to do that.

As an example $etime = [0,1,2] and $value = [3,4,5], and I need [[0,3],[1,4],[2,5]].

Can you please help me with this?

>Solution :

The PHP can combine the data content like this.
You need to multiply the time by 1000 to get the MS that JS/HighChart expects

// Assuming $sensor_data is already populated with your data
$combined_data = array();
foreach ($sensor_data as $data) {
    $etime_millisec = intval($data['etime']) * 1000; // Convert to milliseconds
    $value = floatval($data['value']); // Ensure value is a float
    $combined_data[] = array($etime_millisec, $value);
}

$combined_data_json = json_encode(array_reverse($combined_data), JSON_NUMERIC_CHECK);

Then in the HighChart part you can change to datetime

var chartData = <?php echo $combined_data_json; ?>;

var chartT = new Highcharts.Chart({
    series: [{
        data: chartData
    }],
    xAxis: { 
        type: 'datetime' // Changed from 'categories' to 'datetime'
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading