拆分JSON响应并使用图表数据

时间:2017-05-18 17:52:43

标签: javascript php jquery json ajax

我使用jQuery / AJAX以下列格式从JSON中的PHP后端接收响应:

{"result":[["Cellphone","900"],["Medical","900"],["Repair and Maintenance","3700"],["Travel","867.2"]],"errors":false}

这就是我从PHP后端生成JSON的方式:

    $addresult = "
        SELECT category,SUM(receiptamount)  
        FROM scans              
        GROUP BY category;          
    ";

     if( $result = $mysqli->query($addresult) ) {
        // collect results
        while($row = $result->fetch_all())
        {
            // assign to new array
            // make returnResult an array for multiple results
            $returnResult = $row;
        }
    }

...
echo json_encode(['result' => $returnResult, 'errors' => $errors]);

这是我的jQuery / AJAX success函数:

success: function(response) {
if(!response.errors && response.result) {

    var str = (response.result[1]).toString();
    var str_array = str.split(',');
    for(var i = 0; i < str_array.length; i++) {
       str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
       //alert(str_array[i]);
    }
    var chart = c3.generate({
        bindto: document.getElementById('chart'),
        data: {
            columns: [
                ['Travel', 30],
                ['Accommodation', 130],
                ['Cellphone', 130],
                ['Donation', 130],
                ['Gift', 130],
                ['Medical', 130],
                ['Repair and Maintenance', 130],
                ['Other Expense', 130]
            ],
            type: 'bar'
        },
        bar: {
            width: {
                ratio: 0.5 // this makes bar width 50% of length between ticks
            }
        }
    });

} else {
    myApp.alert('Something went wrong', 'Oops!');
}
}

我想从这些数据中生成图表列名和相应的金额,但我不知道如何。我很感激我得到的任何帮助。

2 个答案:

答案 0 :(得分:1)

因此,根据您发布的json数据,您可以提取如下列:

var json = { 
result : [
    ["Cellphone",900],["Medical",900],["Repair and Maintenance",3700],["Travel",867.2]
],
errors:false
}

var chartColumns= json.result.map(x => x[0] + " " + x[1]);
console.dir(columns);

然后将图表列源设置为chartColumns

var chart = c3.generate({
        bindto: document.getElementById('chart'),
        data: {
            columns: chartColumns,
            type: 'bar'
        },
        bar: {
            width: {
                ratio: 0.5 // this makes bar width 50% of length between ticks
            }
        }
    });

答案 1 :(得分:1)

看起来你可以简单地改变这个:

data: {
    columns: [
        ['Travel', 30],
        ['Accommodation', 130],
        ['Cellphone', 130],
        ['Donation', 130],
        ['Gift', 130],
        ['Medical', 130],
        ['Repair and Maintenance', 130],
        ['Other Expense', 130]
    ],
    type: 'bar'
},

到此:

data: {
    columns: response.result,
    type: 'bar'
},