【问题标题】:C3, D3 Chart with nested JSON Data带有嵌套 JSON 数据的 C3、D3 图表
【发布时间】:2017-12-19 16:13:40
【问题描述】:

我正在尝试使用 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 数据,我会在控制台中得到一个没有错误的空白表。 任何帮助将不胜感激。 在此先感谢科林。

【问题讨论】:

    标签: javascript php json d3.js c3.js


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2015-02-14
      • 2015-08-15
      • 1970-01-01
      • 2013-11-23
      相关资源
      最近更新 更多