mySQL JSON JS Apexcharts

Got something cool to share with AppGini users? Feel free to post it here!
Post Reply
mdannatt
Veteran Member
Posts: 41
Joined: 2020-01-27 17:34

mySQL JSON JS Apexcharts

Post by mdannatt » 2021-10-19 12:41

I have recently started looking at the excellent Apexcharts Library with a view to building a dashboard.

I wrote a mySQL query and then built my JSON data with:

Code: Select all

$result = mysqli_query($query);
    $json_array = array();  
        while($row = mysqli_fetch_assoc($query))  
        {  
            $json_array[] = $row;
        }  
   $json = json_encode($json_array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
   
Which gives me
[{"series":1,"labels":"asset_1"},{"series":2,"labels":"asset_2"}]

I am trying to set up a pie chart, but Apexcharts requires that the JSON data is in the format:
{
series: [1, 2],
labels: ['asset_1', 'asset_2']
}

What is the best/easiest way to change the format of the JSON data? Any help would be greatly appreciated.
Roses are red, Violets are blue, unexpected '}' on line 32

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1635
Joined: 2018-04-01 10:12

Re: mySQL JSON JS Apexcharts

Post by pbottcher » 2021-10-21 16:02

Hi

you may try something like

Code: Select all

	$keys=[];
	$data=[];
	$count=0;
	while($row = mysqli_fetch_assoc($query)) {
		$i=0;
		foreach ($row as $key => $val) {
			$keys[$i]=$key;
			$data[$key][]=$val;
			$i++;
		}
		$count++;
	}

	$data['name']=$keys;
	$i++;
	for ($j=0;$j<$i;$j++) {
		$json_array[]=(array('name' => $data['name'][$j], 'data' => $data[$data['name'][$j]]));
	}
	$json = json_encode($json_array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

Post Reply