Noobster
Noobster

Reputation: 1044

Cannot find proper JSON array syntax for Highcharts

Hope all is well. I am running into a little trouble with setting up a JSON array via PHP and pushing it into Highcharts.

At the moment I generate the array like this:

    $stack[] = array($commname => $countit);
    $stack = json_encode($stack);

When I print_r the array I get the following:

[{"Crude Oil":69},{"Natural Gas":554},{"Liquid Natural Gas":152},{"Power":40},{"Coal":10},{"Weather":21},{"Macroeconomics":67},{"Miscellaneous":45},{"Prices":50},{"Freight":14},{"Forecasts":16}]

I then pass the array to javascript like this:

var stack = <?php echo json_encode( $stack ) ?>;

.. and then pass it into the following highcharts array like this:

var text = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: 1,//null,
            plotShadow: false
        },
        title: {
            text: 'Browser market shares at a specific website, 2014'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            type: 'pie',
            name: 'Browser share',
            data: [
                ]
            }]
        };
text.series[0].data.push(stack);

... But this does not work. I think my array 'stack' is not prepared properly, because highcharts wants it to be in this format: [["Crude oil", 35],["Natural Gas", 45] etc...]

Any pointers as to what I am doing wrong? Thank you!

G.

Upvotes: 0

Views: 97

Answers (3)

Taalaibek M
Taalaibek M

Reputation: 101

You should generate source array like this:

$stack[] = array($commname, $countit);

or like this

$stack[] = array('name' => $commname, 'y' => $countit);

Upvotes: 0

Sebastian Bochan
Sebastian Bochan

Reputation: 37588

You have two ways - form json to this form:

{name:"Crude Oil", y:69}
  • get JSON then use loop and push to new series data array and then refer to it in the highcharts option.

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 1667

Try this jQuery.parseJSON

jQuery.parseJSON()

var stack = <?php echo json_encode( $stack ) ?>;
stack  = jQuery.parseJSON(stack);

Upvotes: 1

Related Questions