How To Read Arrays In API Using Ajax And Jquery - php

I am creating a ticket reservation system. So , in this system I used API to request and get(response) data. But , when I got the response from API , it contains arrays of arrays.
{
"data": [
{
"type": "flight-offer",
"id": "1529553187230--523715719",
"offerItems": [
{
"services": [
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "CMB",
"at": "2018-07-02T03:15:00+05:30"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-02T05:50:00+03:00"
},
"carrierCode": "BA",
"number": "6369",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6369"
},
"duration": "0DT5H5M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-02T06:35:00+03:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-02T12:00:00+01:00"
},
"carrierCode": "BA",
"number": "7007",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "7007"
},
"duration": "0DT7H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "2",
"at": "2018-07-02T14:15:00+01:00"
},
"arrival": {
"iataCode": "DUB",
"terminal": "2",
"at": "2018-07-02T15:40:00+01:00"
},
"carrierCode": "BA",
"number": "5965",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "EI",
"number": "5965"
},
"duration": "0DT1H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
}
]
},
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "DUB",
"terminal": "2",
"at": "2018-07-20T18:00:00+01:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "2",
"at": "2018-07-20T19:20:00+01:00"
},
"carrierCode": "BA",
"number": "5978",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "EI",
"number": "5978"
},
"duration": "0DT1H20M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-20T21:55:00+01:00"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-21T06:40:00+03:00"
},
"carrierCode": "BA",
"number": "7014",
"aircraft": {
"code": "359"
},
"operating": {
"carrierCode": "QR",
"number": "7014"
},
"duration": "0DT6H45M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-21T07:35:00+03:00"
},
"arrival": {
"iataCode": "CMB",
"at": "2018-07-21T15:20:00+05:30"
},
"carrierCode": "BA",
"number": "6366",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6366"
},
"duration": "0DT5H15M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
}
]
}
],
"price": {
"total": "837.46",
"totalTaxes": "464.46"
},
"pricePerAdult": {
"total": "837.46",
"totalTaxes": "464.46"
}
}
]
},
{
"type": "flight-offer",
"id": "1529553187230--1553108626",
"offerItems": [
{
"services": [
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "CMB",
"at": "2018-07-02T03:15:00+05:30"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-02T05:50:00+03:00"
},
"carrierCode": "BA",
"number": "6369",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6369"
},
"duration": "0DT5H5M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-02T06:35:00+03:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-02T12:00:00+01:00"
},
"carrierCode": "BA",
"number": "7007",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "7007"
},
"duration": "0DT7H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "5",
"at": "2018-07-02T14:15:00+01:00"
},
"arrival": {
"iataCode": "DUB",
"terminal": "1",
"at": "2018-07-02T15:40:00+01:00"
},
"carrierCode": "BA",
"number": "830",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "BA",
"number": "830"
},
"duration": "0DT1H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "NLRCAS"
}
}
]
},
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "DUB",
"terminal": "1",
"at": "2018-07-20T16:30:00+01:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "5",
"at": "2018-07-20T18:00:00+01:00"
},
"carrierCode": "BA",
"number": "829",
"aircraft": {
"code": "321"
},
"operating": {
"carrierCode": "BA",
"number": "829"
},
"duration": "0DT1H30M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-20T21:55:00+01:00"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-21T06:40:00+03:00"
},
"carrierCode": "BA",
"number": "7014",
"aircraft": {
"code": "359"
},
"operating": {
"carrierCode": "QR",
"number": "7014"
},
"duration": "0DT6H45M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-21T07:35:00+03:00"
},
"arrival": {
"iataCode": "CMB",
"at": "2018-07-21T15:20:00+05:30"
},
"carrierCode": "BA",
"number": "6366",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6366"
},
"duration": "0DT5H15M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
}
]
}
],
"price": {
"total": "837.46",
"totalTaxes": "464.46"
},
"pricePerAdult": {
"total": "837.46",
"totalTaxes": "464.46"
}
}
]
}
Now I want to read and display these values in the view page. I mean I want to get and display type and id number. Then I tried below steps with laravel. I got all the details with
Console.log(data);.
But, couldn't get any thing into the view page. How can I get values to the view page ??
View page.
<form class="form-horizontal" method="POST" action="#" enctype="multipart/form-data" id="signupForm">
{{ csrf_field() }}
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Origin City : <input type="text" class="form-control" name="origin" value="" id="origin"> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Destination City : <input type="text" class="form-control" name="destination" value=""
id="destination"> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Adults : <select name="st" class="form-control" id="adults">
#for ($i = 1; $i <= 9; $i++)
<option value="{{ $i }}">{{ $i }}</option>
#endfor
</select> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Departure Date :<input class="form-control" type="text" name="departureDate" id="departureDate">
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Return Date :<input class="form-control" type="text" name="returnDate" id="returnDate">
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Access Token : <input type="text" class="form-control" name="bat" value="" id="bat"> <br>
</div>
Pull User Data
<p id="errorModal"></p> <br>
<div id="ghapidata" class="clearfix"></div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#ghsubmitbtn').on('click', function(e){
var origin = $('#origin').val();
var destination = $('#destination').val();
var departureDate = $('#departureDate').val();
var returnDate = $('#returnDate').val();
var adults = $('#adults').val();
var bat = $('#bat').val();
var requri = 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults;
var repouri = 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults;
$.ajax({
url: 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults,
method: 'GET',
headers: {"Authorization": 'Bearer ' + bat},
success: function (data) {
console.log(data);
requestJSON(requri, function(JSON) {
// else we have a user and we display their info
var data = JSON.data;
var type = JSON.type;
var id = JSON.id;
var iataCode = JSON.iataCode;
var outhtml = '<h2>'+data+' <span class="smallname">(#'+type+')</span></h2>';
outhtml = outhtml + '<p>User Type: '+type+'</p></div>';
outhtml = outhtml + '<p>Id: '+id+' - IATA Code: '+iataCode+'<br></p></div>';
outhtml = outhtml + '<div class="repolist clearfix">';
var repositories;
$.getJSON(repouri, function(JSON){
repositories = JSON;
outputPageContent();
});
function outputPageContent() {
outhtml = outhtml + '<p><strong>Repos List:</strong></p> <ul>';
$.each(repositories, function(index) {
outhtml = outhtml + '<li>repositories[index].data.type</li>';
});
outhtml = outhtml + '</ul></div>';
$('#ghapidata').html(outhtml);
} // end outputPageContent()
}); // end requestJSON Ajax call
},
error: function (jQXHR) {
// If status code is 401, access token expired, so
// redirect the user to the login page
if (jQXHR.status == "401") {
$('#errorModal').modal('show');
}
else {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
}
});
});
function requestJSON(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback.call(null, xhr.responseJSON);
}
});
}
});
</script>

Need to parse the response as JSON, then handle it from there:
JSON.parse(data)
$.getJSON(repouri, function(data){
repositories = JSON.parse(data);
data = repositories.data;
type = data.type;
id = data.id;
services = data.offerItems.services; // Referencing the sub objects within
outputPageContent();
});
See here:
http://jsfiddle.net/rhn9cweg/19/
gotta address the sections, can put it into a looping function to handle it a bit cleaner, but you need to parse the data to the function .
---- EDIT ----
to loop through each of the fields:
$.each(repositories, function (key, data) {
console.log(key);
$.each(data, function (index, data) {
console.log('index', data);
});
});
put that to a function and the call it on it self for using an if block to see if the item is an object. (call the function from within the function for a recurring check)

The field type, id are inside data in json array format so you can't read that directly using JSON.type or JSON.id
var data = JSON.data;
var type = data[0].type;
var id = data[0].id;
var iataCode = data[0].iataCode;
Please check browser console for error messages to debug your code

Related

getting Notice: Undefined index: with use of json_decode [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
I am new in PHP. I am trying to get some value from json file and following
This Stackoverflow answer
When I run example given in answer working fine.
I have my.json file like below
{
"quoteSummary": {
"result": [
{
"summaryDetail": {
"maxAge": 1,
"priceHint": {
"raw": 2,
"fmt": "2",
"longFmt": "2"
},
"previousClose": {
"raw": 126,
"fmt": "126.00"
},
"navPrice": {},
"currency": "USD",
"fromCurrency": null,
"toCurrency": null,
"lastMarket": null,
"volume24Hr": {},
"volumeAllCurrencies": {},
"circulatingSupply": {},
"algorithm": null,
"maxSupply": {},
"startDate": {},
"tradeable": false
},
"defaultKeyStatistics": {
"maxAge": 1,
"priceHint": {
"raw": 2,
"fmt": "2",
"longFmt": "2"
},
"lastDividendDate": {
"raw": 1612483200,
"fmt": "2021-02-05"
},
"lastCapGain": {},
"annualHoldingsTurnover": {}
},
"earnings": {
"maxAge": 86400,
"earningsChart": {
"quarterly": [
{
"date": "1Q2020",
"actual": {
"raw": 0.64,
"fmt": "0.64"
},
"estimate": {
"raw": 0.56,
"fmt": "0.56"
}
},
{
"date": "2Q2020",
"actual": {
"raw": 0.64,
"fmt": "0.64"
},
"estimate": {
"raw": 0.51,
"fmt": "0.51"
}
}
],
"currentQuarterEstimate": {
"raw": 0.98,
"fmt": "0.98"
},
"currentQuarterEstimateDate": "1Q",
"currentQuarterEstimateYear": 2021,
"earningsDate": [
{
"raw": 1619568000,
"fmt": "2021-04-28"
},
{
"raw": 1620000000,
"fmt": "2021-05-03"
}
]
},
"financialsChart": {
"yearly": [
{
"date": 2017,
"revenue": {
"raw": 229234000000,
"fmt": "229.23B",
"longFmt": "229,234,000,000"
},
"earnings": {
"raw": 48351000000,
"fmt": "48.35B",
"longFmt": "48,351,000,000"
}
},
{
"date": 2018,
"revenue": {
"raw": 265595000000,
"fmt": "265.6B",
"longFmt": "265,595,000,000"
},
"earnings": {
"raw": 59531000000,
"fmt": "59.53B",
"longFmt": "59,531,000,000"
}
},
{
"date": 2019,
"revenue": {
"raw": 260174000000,
"fmt": "260.17B",
"longFmt": "260,174,000,000"
},
"earnings": {
"raw": 55256000000,
"fmt": "55.26B",
"longFmt": "55,256,000,000"
}
},
{
"date": 2020,
"revenue": {
"raw": 274515000000,
"fmt": "274.51B",
"longFmt": "274,515,000,000"
},
"earnings": {
"raw": 57411000000,
"fmt": "57.41B",
"longFmt": "57,411,000,000"
}
}
],
"quarterly": [
{
"date": "1Q2020",
"revenue": {
"raw": 58313000000,
"fmt": "58.31B",
"longFmt": "58,313,000,000"
},
"earnings": {
"raw": 11249000000,
"fmt": "11.25B",
"longFmt": "11,249,000,000"
}
},
{
"date": "2Q2020",
"revenue": {
"raw": 59685000000,
"fmt": "59.69B",
"longFmt": "59,685,000,000"
},
"earnings": {
"raw": 11253000000,
"fmt": "11.25B",
"longFmt": "11,253,000,000"
}
},
{
"date": "3Q2020",
"revenue": {
"raw": 64698000000,
"fmt": "64.7B",
"longFmt": "64,698,000,000"
},
"earnings": {
"raw": 12673000000,
"fmt": "12.67B",
"longFmt": "12,673,000,000"
}
},
{
"date": "4Q2020",
"revenue": {
"raw": 111439000000,
"fmt": "111.44B",
"longFmt": "111,439,000,000"
},
"earnings": {
"raw": 28755000000,
"fmt": "28.75B",
"longFmt": "28,755,000,000"
}
}
]
},
"financialCurrency": "USD"
}
}
],
"error": null
}
}
I am trying to run like below
$json = file_get_contents('my.json');
$data = json_decode($json, true);
echo $data['quoteSummary']['result']['summaryDetail']['priceHint']['raw'];
but its giving me warning like
Notice: Undefined index: summaryDetail in C:\xampp\htdocs\index.php on line 6
Basically I am looking for get below values from my json file
From summaryDetail, I want
maxAge
priceHint->raw
From defaultKeyStatistics, I want
lastDividendDate->raw
and From Earning, I want
earningsChart->quarterly->actual->raw
Let me know if anyone can help me for same. I am trying from last hour but not able to get idea what I should do .
Thanks!
Your result node is an array of objects, so it be probably:
echo $data['quoteSummary']['result'][0]['summaryDetail']['priceHint']['raw'];

How to access JSON object values using vue steps?

This is step 1. These are the input boxes i want to type. This is the function I created to point each value to input boxes:
getmyEditor: function(){
this.chartType = this.options.chart.type;
this.backgroundColor = this.options.chart.backgroundColor;
this.borderColor = this.options.chart.borderColor;
this.borderWidth = this.options.chart.borderWidth;
this.height = this.options.chart.height;
this.options.xAxis.plotLines = [{
value: this.xPlotLinesvalue,
label: {
text: this.xPlotLinesText,
align: 'center',
style: {
color: 'gray'
}
}}];
Above code i created to access object values. how to apply this values added
text boxes?
{"chart": {
"type": "pie",
"backgroundColor": "#FFFFFF",
"borderColor": "#000",
"borderWidth": 0,
"height": 300,
"inverted": false,
"plotBackgroundColor": "#FFFFFF",
"plotBorderColor": "#FFFFFF",
"plotBorderWidth": 1,
"style": {
"fontFamily": "Open Sans"
},
"polar": ""
},
"title": {
"text": "Title",
"x": -20
},
"table": {
"text": ""
},
"xAxis": {
"max": null,
"categories": [],
"title": {
"text": ""
},
"plotLines": [
{
"value": 0,
"width": 0,
"color": "red",
"label": {
"text": "",
"align": "center",
"style": {
"color": "gray"
}
}
}
]
},
"yAxis": {
"title": {
"text": ""
},
"categories": [],
"min": null,
"max": null,
"plotLines": [
{
"value": 0,
"width": 0,
"color": "red",
"label": {
"text": "",
"align": "center",
"style": {
"color": "gray"
}
}
}
]
},
"zAxis": "",
"tooltip": {
"valueDecimals": 0,
"valuePrefix": "",
"valueSuffix": "",
"padding": 8
},
"legend": {
"enabled": true,
"layout": "vertical",
"align": "right",
"verticalAlign": "middle",
"borderWidth": 0
},
"credits": {
"enabled": false
},
"plotOptions": {
"series": {
"color": "#582b6e",
"stacking": "",
"point": {
"events": {}
}
},
"scatter": {
"marker": {
"radius": 4,
"states": {
"hover": {
"enabled": true,
"lineColor": "rgb(100,100,100)"
}
}
},
"states": {
"hover": {
"marker": {
"enabled": false
}
}
},
"tooltip": {
"headerFormat": "<b>{series.name}</b><br>",
"pointFormat": "{point.x} , {point.y} ",
"x_unit": "",
"y_unit": ""
}
}
},
"series": [
{
"name": "Brands",
"colorByPoint": true,
"data": [
{
"name": "IE",
"y": 56.33
},
{
"name": "Chrome",
"y": 24.03,
"sliced": true,
"selected": true
},
{
"name": "Firefox",
"y": 10.38
},
{
"name": "Safari",
"y": 4.77
},
{
"name": "Opera",
"y": 0.91
},
{
"name": "Other",
"y": 0.2
}
]
}
],
"lang": {
"noData": "NO DATA AVAILABLE!"
},
"noData": {
"style": {
"fontWeight": "bold",
"fontSize": "15px",
"color": "#303030"
}
}
}
I'm trying to access (point to text boxes) this object using vue, but it's not working yet. How to do that correctly? I point each object value using this vue function inside method.
This is i want final output: This object view inside textarea if i change text area object value then that value will going to above input boxes.

Using PHP, how can i find the number of occurences of the [departs_at] field?

{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
},
This is json data fetched from live flights query. I want to be able to determine the number of stops for each flight using the [depart_at] field. So I have been struggling to get the number of occurrences of the [depart_at] field so as to derive how many stops(layovers) for each flight. I have already converted to php using the code below: But I am not getting the count.
<?php foreach ($itinerary['outbound']['flights'] as $flight ){
echo count($flight['flights']);
}?>
You can try like this:
$json = '{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
}';
echo substr_count($json, 'departs_at');
You can try that way.
$countDepartsAt = 0;
foreach ($itinerary['outbound']['flights'] as $flight ){
if(array_key_exists('departs_at', $flight)) {
$countDepartsAt++;
}
}
echo $countDepartsAt;

How to create a combo chart (bar and line) with fusioncharts using data from MySQL database?

I found this code online to do basically everything I was looking for except they are not using data from a MySQL database where as I am. Here is their code:
{
"chart": {
"caption": "Inventory by Product Categories",
"bgcolor": "FFFFFF",
"plotgradientcolor": "",
"showalternatehgridcolor": "0",
"showplotborder": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"pyaxisname": "Cost of Inventory",
"syaxisname": "Units in Inventory",
"numberprefix": "$",
"labeldisplay": "STAGGER",
"slantlabels": "1",
"canvasborderalpha": "0",
"legendshadow": "0",
"legendborderalpha": "0",
"showborder": "0"
},
"categories": [
{
"category": [
{
"label": "Seafood",
"labelPadding": 0
},
{
"label": "Beverages",
"labelPadding": 12
},
{
"label": "Condiments",
"labelPadding": 0
},
{
"label": "Dairy Products",
"labelPadding": 12
},
{
"label": "Confections",
"labelPadding": 0
},
{
"label": "Meat/Poultry",
"labelPadding": 12
},
{
"label": "Grains/Cereals",
"labelPadding": 0
},
{
"label": "Produce",
"labelPadding": 12
}
]
}
],
"dataset": [
{
"seriesname": "Cost of Inventory",
"color": "008ee4",
"data": [
{
"value": "13510"
},
{
"value": "12480"
},
{
"value": "12024"
},
{
"value": "11271"
},
{
"value": "10392"
},
{
"value": "5729"
},
{
"value": "5594"
},
{
"value": "3549"
}
]
},
{
"seriesname": "Quantity",
"parentyaxis": "S",
"renderas": "Line",
"color": "f8bd19",
"data": [
{
"value": "701"
},
{
"value": "559"
},
{
"value": "507"
},
{
"value": "393"
},
{
"value": "386"
},
{
"value": "165"
},
{
"value": "258"
},
{
"value": "100"
}
]
}
]
}
This makes sense, but it's changing this JSON code to accept data from a database instead of hardcoding this that is difficult for me.
Here is the relevent part of my code:
<?php
$strQuery2 = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = 'WE' GROUP BY ScrapDate ORDER BY ScrapDate";
// Execute the query, or else return the error message.
$result2 = $dbhandle->query($strQuery2) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result2) {
// The `$arrData` array holds the chart attributes and data
$arrData2 = array(
"chart" => array(
"caption" => "WE Last Week Scrap Quantity",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0",
"xAxisName"=> "Day",
"yAxisName"=> "Quantity"
)
);
$arrData2["data"] = array();
// Push the data into the array
while($row2 = mysqli_fetch_array($result2)) {
array_push($arrData2["data"], array(
"label" => $row2["ScrapDate"],
"value" => $row2["Quantity"],
// "link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData2 = json_encode($arrData2);
$columnChart2 = new FusionCharts("column2D", "chart2" , 600, 300, "chart-2", "json", $jsonEncodedData2);
// Render the chart
$columnChart->render();
$columnChart2->render();
// Close the database connection
$dbhandle->close();
}
?>
As of right now, I can get data from the MySQL database and put it into a graph very easily. Now I want to add 1 more dataset, how do I do this?
To dynamically update the chart, following methods turns very useful:
getJSONData: Fetches chart data in the JSON format.
setJSONData: Sets chart data in the JSON data format
A sample implementation is shown in the below snippet. The chart is initially rendered as the default column2d chart. Once the Add Area button is clicked, an area dataset gets visually updated. Similarly on clicking the Add Line button to add a line dataset. The Reset button restores to original column only visual.
var visitChart,
areaBtn = document.getElementById('area'),
lineBtn = document.getElementById('line'),
resetBtn = document.getElementById('reset');
FusionCharts.ready(function() {
visitChart = new FusionCharts({
type: 'mscombi2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Actual Revenues, Targeted Revenues & Profits",
"subcaption": "Last year",
"xaxisname": "Month",
"yaxisname": "Amount (In USD)",
"numberprefix": "$",
"theme": "fint"
},
"categories": [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}],
"dataset": [{
"seriesname": "Actual Revenue",
"data": [{
"value": "16000"
}, {
"value": "20000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "15000"
}, {
"value": "21000"
}, {
"value": "16000"
}, {
"value": "20000"
}, {
"value": "17000"
}, {
"value": "25000"
}, {
"value": "19000"
}, {
"value": "23000"
}]
}]
}
}).render();
});
areaBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Profit",
"renderas": "area",
"showvalues": "0",
"data": [{
"value": "4000"
}, {
"value": "5000"
}, {
"value": "3000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "7000"
}, {
"value": "1000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "8000"
}, {
"value": "2000"
}, {
"value": "7000"
}]
});
visitChart.setJSONData(json);
areaBtn.disabled = true;
});
lineBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Projected Revenue",
"renderas": "line",
"showvalues": "0",
"data": [{
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "20000"
}, {
"value": "21000"
}, {
"value": "22000"
}, {
"value": "23000"
}]
});
visitChart.setJSONData(json);
lineBtn.disabled = true;
});
resetBtn.addEventListener('click', function() {
var dataset,
len,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
if ((len = dataset.length) > 1) {
dataset.splice(1, len - 1);
}
visitChart.setJSONData(json);
areaBtn.disabled = false;
lineBtn.disabled = false;
});
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<button id='area'>Add Area</button>
<button id='line'>Add Line</button>
<button id='reset'>Reset</button>
<span id="chart-container">FusionCharts XT will load here!</span>
The data getting appended might be fetched from a database in a similar manner stated above.

Making a tree map with JSON data (Highcharts)

I am trying to bring data from the database to this Highcharts tree map, I have no idea how to format the JSON part of the code. When there is a clear xAxis and yAxis it is relatively easy. We use a php assembler to get all of the data from the query. I took the code straight from a Highcharts column chart with JSON that was working normally, I tried myself to update it and it keeps telling me the $.getJSON bit is an unexpected identifier.
$(function () {
// Drop-in fix:
Highcharts.seriesTypes.treemap.prototype.getExtremesFromAll = true;
$('#container').highcharts({
colorAxis: {
minColor: ' #000000',
maxColor: '#ffffff'
},
tooltip: {
backgroundColor: '#fffff',
formatter: function () {
return this.point.name + ":" + this.point.value;
}
}
$.getJSON("/charts/data/homepage-charts-data.php?<?php echo $_SERVER['QUERY_STRING']; ?>", function(json) {
options.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
});
The code that formats the data (from: /charts/data/homepage-charts-data.php)
function displayJsonHomepageBallotMeasuresDataChart ($aaQuery) {
global $NIMSPv4;
$result = $NIMSPv4->query("$aaQuery");
$categories = array();
$categories['name'] = 'Election_Jurisdiction';
$series = array();
$series['name'] = 'Total_$';
while($row = $result->fetch_assoc()) {
$categories['data'][] = $row['Election_Jurisdiction'];
$series['data'][] = $row['Total_$'];
}
$result = array();
array_push($result,$categories);
array_push($result,$series);
print json_encode($result, JSON_NUMERIC_CHECK);
} // END CHART FUNCTION
Update: Here is the JSON I am trying to pull data from. Election_Jurisdiction and Total_$ is what I am trying to access for now, Candidate and Office_Sought could also be brought down as well considering it is a tree map and I will need to show the race.
{
"metaInfo": {
"format": "json",
"completeness": {
"allReports": "297",
"availableReports": "297",
"completeReports": "300",
"incompleteAvailable": "-3",
"lastUpdated": "2015-11-04 09:23:28",
"mostRecentReportDate": "2013-01-31"
},
"paging": {
"pageLink": "p=0",
"minPage": 0,
"currentPage": 0,
"maxPage": 0,
"totalPages": 1,
"totalRecords": "3",
"recordsPerPage": 100,
"recordsThisPage": 3
},
"grouping": {
"groupLink": "gro=c-t-id",
"currentGrouping": {
"c-t-id": "Candidate (General)"
},
"availableGrouping": {
"f-s": "Filing Jurisdiction (General)",
"f-eid": "Filer (General)",
"f-y": "Filing Year (Advanced)",
"c-t-i": "Incumbency Data (Advanced)",
"c-t-icod": "Incumbency Advantage (Advanced)",
"d-nme": "Original Name (Advanced)",
"d-amt": "Amount (Advanced)",
"d-dte": "Date (Advanced)",
"d-ludte": "Last Updated (Advanced)",
"d-typ": "Type of Transaction (Advanced)",
"d-llink": "Lobbying Entity? (Advanced)",
"d-ad-str": "Street (Advanced)",
"c-t-sts": "Status of Candidate (Candidates)",
"d-id": "Record (Contributors)",
"d-eid": "Contributor (Contributors)",
"d-et": "Type of Contributor (Contributors)",
"d-ccg": "Broad Sector (Contributors)",
"d-cci": "General Industry (Contributors)",
"d-ccb": "Specific Business (Contributors)",
"d-ad-cty": "City (Contributors)",
"d-ad-st": "State (Contributors)",
"d-ad-zip": "Zip (Contributors)",
"d-ins": "In-Jurisdiction (Contributors)",
"d-empl": "Employer (Contributors)",
"d-occupation": "Occupation (Contributors)"
}
},
"sorting": {
"sortLink": "so=u-tot&sod=0",
"currentSorting": {
"u-tot": "Total_$"
},
"sortingDirection": "descending",
"availableSorting": {
"c-t-id": "Candidate",
"c-t-pt": "Specific_Party",
"c-t-p": "General_Party",
"s": "Election_Jurisdiction",
"y": "Election_Year",
"c-r-t": "Election_Type",
"c-r-osid": "Office_Sought",
"c-t-ftsts": "Election_Status",
"c-t-ico": "Incumbency_Status",
"u-rec": "#_of_Records"
}
},
"recordFormat": {
"request": "c-r-id=16739",
"Candidate": {
"token": "c-t-id",
"id": "token value",
"Candidate": "display value"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "token value",
"Candidate_Entity": "display value"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "token value",
"Specific_Party": "display value"
},
"General_Party": {
"token": "c-t-p",
"id": "token value",
"General_Party": "display value"
},
"Election_Jurisdiction": {
"token": "s",
"id": "token value",
"Election_Jurisdiction": "display value"
},
"Election_Year": {
"token": "y",
"id": "token value",
"Election_Year": "display value"
},
"Election_Type": {
"token": "c-r-t",
"id": "token value",
"Election_Type": "display value"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "token value",
"Office_Sought": "display value"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "token value",
"Election_Status": "display value"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "token value",
"Incumbency_Status": "display value"
},
"#_of_Records": {
"#_of_Records": "display value"
},
"Total_$": {
"Total_$": "display value"
}
}
},
"records": [
{
"record_id": 1,
"request": "c-r-id=16739&c-t-id=76674",
"Candidate": {
"token": "c-t-id",
"id": "76674",
"Candidate": "BUTLER, MACK N"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881718",
"Candidate_Entity": "BUTLER, MACK N"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "139",
"Specific_Party": "REPUBLICAN"
},
"General_Party": {
"token": "c-t-p",
"id": "2",
"General_Party": "Republican"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Won-General",
"Election_Status": "Won-General"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "197"
},
"Total_$": {
"Total_$": "94700.08"
}
},
{
"record_id": 2,
"request": "c-r-id=16739&c-t-id=76438",
"Candidate": {
"token": "c-t-id",
"id": "76438",
"Candidate": "MCGLAUGHN, BETH"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881720",
"Candidate_Entity": "MCGLAUGHN, BETH"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "33",
"Specific_Party": "DEMOCRATIC"
},
"General_Party": {
"token": "c-t-p",
"id": "1",
"General_Party": "Democratic"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Lost-General",
"Election_Status": "Lost-General"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "39"
},
"Total_$": {
"Total_$": "22537.65"
}
},
{
"record_id": 3,
"request": "c-r-id=16739&c-t-id=28927",
"Candidate": {
"token": "c-t-id",
"id": "28927",
"Candidate": "MCHUGH, ROB"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881719",
"Candidate_Entity": "MCHUGH, ROB"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "139",
"Specific_Party": "REPUBLICAN"
},
"General_Party": {
"token": "c-t-p",
"id": "2",
"General_Party": "Republican"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Lost-Primary",
"Election_Status": "Lost-Primary"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "0"
},
"Total_$": {
"Total_$": "0.00"
}
}
]
}

Categories