I have a JSON object which is retrieved from MySQL using PHP.It is as follows:
{
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, null, null]
}
The content can vary as it totally depends on data retrieved from database at any point of time.Now in Javascript I 'm plotting HighCharts, and need to use the data retrieved from JSON object, i.e. I' m having series:
[{
name: 'A',
data: [1, 2, 3]
}, {
name: 'B',
data: [4, 5, 6]
}, {
name: 'C',
data: [7, , ]
}]
Here I have typed array data, but it has to be dynamic, as I'll not be knowing the contents of the array. My expected output is as follows:
[{
name: ' A ',
data: Array[' A ']
// should give the data of [1,2,3]
}, {
name: ' B ',
data: Array[' B ']
}, {
name: ' C ',
data: Array[' C ']
}]
Kindly suggest how to proceed?
You can use JSON_NUMERIC_CHECK
http://php.net/manual/en/json.constants.php to form proper associative array in php.
For current scenario you can update you json data dynamically
{
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, null, null]
}
to required form
[{
"name": "A",
"data": [1, 2, 3]
}, {
"name": "B",
"data": [4, 5, 6]
}, {
"name": "C",
"data": [7, 0, 0]
}]
by using code below
var dataJ = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, null, null]
}
var highchartsData = []; //series data
Object.keys(dataJ).map((el) => {
highchartsData.push({
name: el,
data: dataJ[el].map(Number) //convert to number
})
})
var dataJ = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, null, null]
}
var highchartsData = [];
Object.keys(dataJ).map((el) => {
highchartsData.push({
name: el,
data: dataJ[el].map(Number)
})
})
Highcharts.chart('container', {
title: {
text: 'Solar Employment Growth by Sector, 2010-2016'
},
subtitle: {
text: 'Source: thesolarfoundation.com'
},
yAxis: {
title: {
text: 'Number of Employees'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
series: highchartsData,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
#container {
min-width: 310px;
max-width: 800px;
height: 400px;
margin: 0 auto
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>
</div>
After looking at your fiddle I think I know what's wrong. Your server response object has the data
as an array of strings. Apparently highcharts will not automatically parse these strings as numbers, but you can map the array to numbers as such:
series: [{
name: 'A',
data: myo['A'].map(parseInt)
}, {
name: 'B',
data: myo['B'].map(parseInt)
}, {
name: 'C',
data: myo['C'].map(parseInt)
}]