嵌套 JSON 数据的 C3、D3 图表

C3, D3 Chart with nested JSON Data

我正在尝试使用 C3.js 创建条形图,数据通过 PHP 从 mySQL database 提取并返回到 JS as JSON。 PHP 代码搜索排好序的列并将所有相关列加在一起以得到 {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));

结果 JSON 输出是:

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

但是,我无法在图表中显示此数据。 下面的代码工作正常,一切都按预期显示。

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
        }
    });

但是,一旦我使用变量 json_data,或者如果我手动复制生成的 JSON 数据,我会在控制台中得到一个空白 table,没有任何错误。 任何帮助将不胜感激。 提前致谢,科林。

您可以使用 array_values() 将数组转换为数字类型:

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