Trying to group tow columns and and populate it as a particular series on highcharts. my code not grouping columns, And showing all data as a single series.
$query = $db->Prepare("SELECT class, SUM(marks), DATE(date_column) as
dates FROM classes GROUP BY class,DATE(date_column)");
$query->execute();
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$date = $row['dates'];
$dates[] = $row['dates'];
$class[] = $row['class'];
$marks[] = $row['SUM(marks)'];
$output[] = array($date,(int)$marks);
}
echo json_encode(array('date'=>$dates,'marks'=>$marks, 'name' => $class));
JS
<script>
$(document).ready(function () {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.dates
},
series : [{
"name" : data.name,
"data": data.marks
}],
});
});
});
});
</script>
Table
Expected output in JSFiddle
data response
date: ["2019-02-07", "2019-02-09", "2019-02-12", "2019-02-08", "2019-02-12",
"2019-02-13", "2019-03-13",…]
marks: ["45", "166", "78", "64", "64", "627", "87", "352"]
name: ["claas 1", "claas 1", "claas 1", "class 2", "class 2", "class 2", "class 3", "class 3"]
By seeing your fiddle the expected output you want for HighCharts is as follow:
1: Category Data:
It should be an array of dates.
Make sure you remove duplicates and order them in ascending/descending order whichever you want, to see a continuous graph.
"categories":["2019-02-07", "2019-02-08", "2019-02-09", "2019-02-12", "2019-02-13", "2019-02-14"]
2: Series Data:
It would be an array of object, where each object contains two properties name and data.
Data should have n no of values if your categories array has n values and each corresponds to same index.
As we don't have data for each date for each class, we would add 0 there.
So data would look like
"series":[
{
"name":"class 1",
"data":[45,0,166,78,0,0]
},
{
"name":"class 2",
"data":[0,64,0,64,627,0]
},
{
"name":"class 3",
"data":[0,0,0,0,87,352]
}
]
Final Fiddle which can be achieved by PHP using below code:
$arrDates = [];
$arrClass = [];
$arrData = [];
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$arrDates[] = $row['dates'];
$arrClass[] = $row['class'];
$arrData[$row['class'] . ':' . $row['dates']] = $row['marks']; // to identify for which date & class this marks belong to, we can directly search for index.
}
$arrDates = array_unique($arrDates);
sort($arrDates);
$arrClass = array_unique($arrClass);
// Create series data
$arrSeriesData = [];
foreach($arrClass as $strClass){
$tempArr = ['name' => $strClass];
foreach($arrDates as $strDate){
$tempArr['data'][] = isset($arrData[$strClass . ':' . $strDate]) ? intval($arrData[$strClass . ':' . $strDate]) : 0;
}
$arrSeriesData[] = $tempArr;
}
$response = ['categories' => $arrDates, 'series' => $arrSeriesData];
echo json_encode($response);
Output:
{"categories":["2019-02-07","2019-02-08","2019-02-09","2019-02-12","2019-02-13","2019-02-14"],"series":[{"name":"class 1","data":[45,0,166,78,0,0]},{"name":"class 2","data":[0,64,0,64,627,0]},{"name":"class 3","data":[0,0,0,0,87,352]}]}
Update your javascript code to reflect the above
$(document).ready(function() {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.categories
},
series: data.series,
});
});
});
});
Related
I am trying to add a dynamic select list to a Datatables Editor form. This is what I have tried:
var discipline_options = [];
$.getJSON('program_data/get_disciplines.php', function (data) {
$.each(data, function (index) {
discipline_options.push({
value: data[index].value,
label: data[index].text
});
});
editor.field( 'discipline_outcome.discipline_fk' ).update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline_outcome.discipline_fk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
The get_disciplines.php script is:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("label"=>$row['discipline'], "value"=>$row['discipline_pk']);
}
$temp = array('disciplines[].discipline_pk'=>$data);
$json = array('options'=>$temp);
echo json_encode($json);
This script returns the following JSON, but the select list is still empty:
{
"options": {
"disciplines[].discipline_pk": [
{
"label": "Emergency Medicine",
"value": "1"
},
{
"label": "General Practice",
"value": "2"
},
{
"label": "Internal Medicine",
"value": "3"
}
]
}
}
I got it working using:
var discipline_options = [];
$.getJSON("program_data/get_disciplines.php", function(data) {
var option = {};
$.each(data, function(i,e) {
option.label = e.text;
option.value = e.id;
discipline_options.push(option);
option = {};
});
}
).done(function() {
editor.field('discipline.discipline_pk').update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline.discipline_pk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
and the get_disciplines.php:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("text"=>$row['discipline'], "id"=>$row['discipline_pk']);
}
echo json_encode($data);
I am create the js tree to show the folder path name, and my problem is how to check the condition if database table status is 0(inactive) then will show the line-through in the js tree. Else table status is 1(active) just back to normal. Below is my coding:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>",
"category" => $row['category'],
"status" => $row['status'], // status 0 is inactive, status 1 is active
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?>
<script style="text/javascript">
var StrikeNodes = function(nodelist) {
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(parseInt(n.text.substr(0, 3), 10));
tree.redraw_node(n.id); //Redraw tree
StrikeNodes(n.children); //Update leaf nodes
});
};
var getStrike = function(i) {
if (status = '0' ) {
return "line-through;";
} else {
return "";
}
};
$('#folder_jstree').bind('load_node.jstree', function(e, data) {
var tree = $('#folder_jstree').jstree(true);
StrikeNodes(tree.get_json());
});
</script>
Now my output show all the all the line-through in the js tree, not detect which is active or inactive.
My working JSFiddle code here: https://jsfiddle.net/ason5861_cs/9x0dsotz/3/
Hope someone can guide me which part I am getting wrong.
looking at your code. you are not comparing the status it should be status == '0' instead of status = '0'
also there is available option that jstree provided. data option this can be anything you want. it is metadata you want attached to the nod. you will be able to access and modify it any time later - it has no effect on the visuals of the node.
[{
"id": "1",
"parent": "#",
"text": "100 PENTADBIRAN <span id='category'>JTM<\/span>",
"category": "JTM",
"data": { "status": 0 },
"state": {
"selected": false,
"opened": false
}
}]
var StrikeNodes = function(nodelist) {
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(n.data.status);
tree.redraw_node(n.id); //Redraw tree
StrikeNodes(n.children); //Update leaf nodes
});
};
var getStrike = function(status) {
if (status == 0) {
return "line-through;";
}
return "";
};
here's i've edited your fiddle https://jsfiddle.net/Hafizu/1xt7bhem/11/
I am trying to pull financial stock data of multiple companies from CSVs and display the data as separate series in a Highcharts/Highstocks line chart. I have the sources setup and I am able to pull data + convert to JSON, but I am having trouble passing the data off to Highcharts. I believe I am not using the most efficient method of preparing the data for Highcharts use, and I am hoping someone can give me direction on what I've done incorrectly. Please take a look at my code and make me aware of any inefficiencies or glaring errors you see.
PHP code:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB');
$stocks_data = array();
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$MSFT = json_encode($MSFT);
foreach($AAPL_data as $val){
$AAPL[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$AAPL = json_encode($AAPL);
foreach($FB_data as $val){
$FB[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$FB = json_encode($FB);
JS code:
$(function () {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
seriesOptions[0] = {
name: 'MSFT',
data: <? php echo $MSFT; ?>
};
seriesOptions[1] = {
name: 'AAPL',
data: <? php echo $AAPL; ?>
};
seriesOptions[2] = {
name: 'FB',
data: <? php echo $FB; ?>
};
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
If you have any questions or need further information, please let me know with a comment.
Thanks
BTW: I have all necessary assets included for Highcharts to work; when I replace my JS + PHP with example code from the Highcharts site, it works beautifully. So the problem clearly lies in my JS + PHP code.
Alright, I believe I found the problem, it lies in the way that you are storing each individual point in the array.
Instead of this (which is passing a string x,y separated by a comma):
strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close'];
You are going to want to use something like this (Highcharts accepts arrays or associative arrays):
array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
That will store the X and Y variables as an array instead of comma separated string for the javascript to pass as data.
My data is displayed in console, but does not display in ExtJs tree?
My php file
$data = array();
$sql = "";
if (!isset($_POST['node'])) {
// first select the top node that have no parent
$sql = "SELECT id_no,value_data FROM extjs_tree WHERE parent IS NULL";
} else {
// select data with parent_id = $_POST['node']
$sql = "SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $_POST['node'] ."'";
}
$q = mysql_query($sql);
while ($r = mysql_fetch_array($q)) {
// check if have a child node
$qq = mysql_query("SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $r['id'] ."'");
if (mysql_num_rows($qq) > 0) {
// if have a child
$r['leaf'] = false;
$r['cls'] = 'folder';
} else {
// if have no child
$r['leaf'] = true;
$r['cls'] = 'file';
}
$data[] = $r;
}
echo json_encode($data);
My JS file
Ext.require([
'Ext.tree.*',
'Ext.data.*',
'Ext.tip.*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var store = Ext.create('Ext.data.TreeStore', {
proxy: {
type:'ajax',
actionMethods:'post',
url:'get-nodes.php'
},
root: {
text: 'Root Node',
id: 'root_node',
expanded: true
},
folderSort: true,
sorters: [{
property:'text',
direction:'ASC'
}]
});
var tree = Ext.create('Ext.tree.Panel', {
store: store,
renderTo: 'tree_el',
height: 300,
width: 250,
title: 'Products Display'
});
});
I am getting the tree properly, I can see the data in the console. But I cannot see ExtJs displaying the values??
My present result
My expected result should be
In your case you can also add following field to your store:
{
name: 'text',
mapping: 'value'
}
Every item of response has to have text field in it. As I can see from your request-response images You don't send text field. Response should be looking like the following one:
[{
"id": 2,
"text": "Fruits", // this field is required
...
},
...
]
I have a Highstock graph and I've got the data from a MySQL database like is shown in this example.
The date field is a MySQL timestamp. When I situate the cursor over a value, only the year is shown instead of (Day, month day, year).
Any idea about why only the year is shown?
I'm using Codeigniter framework and the server side code looks like:
$sql = "SELECT UNIX_TIMESTAMP(sop_date)*1000 AS sop_date, sop_price
FROM share
INNER JOIN share_operation
ON share_operation.sop_idsha = share.sha_id
INNER JOIN share_operation_type
ON share_operation_type.sot_id = share_operation.sop_idsot";
$params = array($sha_idcon, $sha_idwal);
$query = $this->db->query($sql, $params);
if ($query->num_rows() > 0) {
$data = array();
foreach ($query->result() as $i => $row) {
$data[] = "[$row->sop_date, $row->sop_price]";
}
return ($data);
}
Client side:
$(document).ready(function() {
Highcharts.setOptions({
lang: {
months: ['Gener', 'Febrer', 'Març', 'Abril', 'Maig', 'Juny',
'Juliol', 'Agost', 'Setembre', 'Octubre', 'Novembre', 'Desembre'],
weekdays: ['Dilluns', 'Dimarts', 'Dimecres', 'Dijous', 'Divendres', 'Dissabte', 'Diumenge'],
rangeSelectorFrom: 'Des de',
rangeSelectorTo: 'Fins'
}
});
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'graphic'
},
rangeSelector : {
selected : 1
},
title : {
text : 'Xisco'
},
xAxis : {
maxZoom : 14 * 24 * 3600000 // fourteen days
},
series : [{
name : 'Xisco',
data : [<?php echo join($data, ',') ?>],
tooltip: {
yDecimals: 2
}
}]
});
});
Enforcing a formatting might solve this issue.
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%e. %b %Y', this.x);
}
}
More information is in the documentation.
Hope this helps.