user1984696
user1984696

Reputation: 31

C3, D3 Chart with nested JSON Data

I am trying to create a bar chart using C3.js with data pulled via PHP from a mySQL database and returned to JS as JSON. The PHP code searches a sorted column and adds all of a related column together to end up with an array of {category:name, total_purchased:value}

$category_data_sql = "SELECT `category`, `total_purchased` FROM `item` ORDER BY `category`";
$category_data_result = $mysqli->query($category_data_sql);

$data = array();
$key = 0;
foreach ($category_data_result as $item) {
    $key = $item['category'];
    if (!array_key_exists($key, $data)) {
        $data[$key] = array(                
            'category' => $item['category'],
            'total_purchased' => $item['total_purchased'],
        );

    } else {
        $data[$key]['total_purchased'] = $data[$key]['total_purchased'] + $item['total_purchased'];

    }

    $key++;
}
print_r(json_encode($data));

The resulting JSON output is:

{
    "BRACELET": {
        "category": "BRACELET",
        "total_purchased": 26
    },
    "SALESMAT": {
        "category": "SALESMAT",
        "total_purchased": 4
    },
    "TOPPING": {
        "category": "TOPPING",
        "total_purchased": 48
    }
}

But, I am not able to display this data in the chart. The below code works fine, everything displays as expected.

var json_data = (<?php echo json_encode($data); ?>);
    var chart = c3.generate({
        bindto: '#chart',
        data: {
            x: 'category',                        
            json: [
                    {
                        "category": "BRACELET",
                        "total_purchased": 26
                    },
                    {
                        "category": "SALESMAT",
                        "total_purchased": 4
                    },
                    {
                        "category": "TOPPING",
                        "total_purchased": 48
                    },
                    {
                        "category": "NECKLACE",
                        "total_purchased": 29
                    }
            ],
            type: 'bar',
            keys: {
                x: 'category',
                value: [ "total_purchased" ]
            }
        },
        axis: {
            x: {
                type: "category"
            }
        },

        bar: {
            space: 0.25
        }
    });

But once I use the variable json_data or if I manually copy in the resulting JSON data I get a blank table with no errors in the console. Any help would be greatly appreciated. Thanks in advance, Colin.

Upvotes: 1

Views: 447

Answers (1)

astrangeloop
astrangeloop

Reputation: 1520

You could use array_values() to convert your array to a numeric type:

$json_data = json_encode(array_values($data));

Upvotes: 1

Related Questions