MagicSeaweed API JSON Array - php

The MSW API states:
Our API follows RESTful convention. Querying for information for a location is as simple as calling: http://magicseaweed.com/api/YOURAPIKEY/forecast/?spot_id=10
You’ll receive a JSON array consisting of a series of data representing the forecast for specific timeframes, looking like this:
[
{
"timestamp": 1367366400,
"localTimestamp": 1367366400,
"issueTimestamp": 1367366400,
"fadedRating": 0,
"solidRating": 0,
"swell": {
"minBreakingHeight": 1,
"absMinBreakingHeight": 0.504,
"maxBreakingHeight": 1,
"absMaxBreakingHeight": 0.784,
"unit": "ft",
"components": {
"combined": {
"height": 1.6,
"period": 5,
"direction": 252.47,
"compassDirection": "ENE"
},
"primary": {
"height": 0.5,
"period": 7,
"direction": 92.49,
"compassDirection": "W"
},
"secondary": {
"height": 0.2,
"period": 9,
"direction": 52.9,
"compassDirection": "SW"
},
"tertiary": {
"height": 1.5,
"period": 5,
"direction": 248.62,
"compassDirection": "ENE"
}
}
},
"wind": {
"speed": 6,
"direction": 221,
"compassDirection": "NE",
"chill": 32,
"gusts": 9,
"unit": "mph"
},
"condition": {
"pressure": 1026,
"temperature": 39,
"weather": "10",
"unitPressure": "mb",
"unit": "f"
},
"charts": {
"swell": "htt://chart-1-us.msw.ms/wave/750/1-1367366400-1.gif",
"period": "htt://chart-1-us.msw.ms/wave/750/1-1367366400-2.gif",
"wind": "htt://chart-1-us.msw.ms/gfs/750/1-1367366400-4.gif",
"pressure": "htt://chart-1-us.msw.ms/gfs/750/1-1367366400-3.gif",
"sst": "htt://chart-1-us.msw.ms/sst/750/1-1367366400-10.gif"
}
},
{
"timestamp": 1367377200,
"localTimestamp": 1367377200,
"issueTimestamp": 1367366400,
"fadedRating": 0,
"solidRating": 0,
"swell": {
"minBreakingHeight": 0,
"absMinBreakingHeight": 0.384,
"maxBreakingHeight": 1,
"absMaxBreakingHeight": 0.6,
"unit": "ft",
"components": {
"combined": {
"height": 1.8,
"period": 4,
"direction": 266.06,
"compassDirection": "E"
},
"primary": {
"height": 0.4,
"period": 6,
"direction": 92.53,
"compassDirection": "W"
},
"secondary": {
"height": 0.2,
"period": 9,
"direction": 52.72,
"compassDirection": "SW"
},
"tertiary": {
"height": 1.8,
"period": 4,
"direction": 258.73,
"compassDirection": "ENE"
}
}
},
"wind": {
"speed": 5,
"direction": 255,
"compassDirection": "ENE",
"chill": 34,
"gusts": 7,
"unit": "mph"
},
"condition": {
"pressure": 1025,
"temperature": 41,
"weather": "10",
"unitPressure": "mb",
"unit": "f"
},
"charts": {
"swell": "htt://chart-1-us.msw.ms/wave/750/1-1367377200-1.gif",
"period": "htt://chart-1-us.msw.ms/wave/750/1-1367377200-2.gif",
"wind": "htt://chart-1-us.msw.ms/gfs/750/1-1367377200-4.gif",
"pressure": "htt://chart-1-us.msw.ms/gfs/750/1-1367377200-3.gif",
"sst": "htt://chart-1-us.msw.ms/sst/750/1-1367377200-10.gif"
}
}, THIS CONTINUES ON UNTIL THE END OF THE ARRAY
How do I go about calling on the JSON Array and how can I assign a variable to each item (or access each item to use later in html etc.)?
Thanks.

OK, so if you're using PHP it's easy to access the JSON data, just use the json_decode function so you can access the data as a PHP array and work with it easily.
Your code should follow this tasks:
Load the JSON data from the MagicSeaweed API URL;
Decode the JSON into a PHP array;
Process the PHP array and retrieve the fields you want.
In the following code you just need to replace MYAPIKEY with your real APIKEY, uncomment the line $json = file_get_contents("magicseaweed.com/api/MYAPIKEY/forecast/?spot_id=10"); and comment the other line that's assigning the $json variable with the JSON subset example.
Code:
<?php
// You should fetch the JSON data from the remote location the same
// $json = file_get_contents("magicseaweed.com/api/MYAPIKEY/forecast/?spot_id=10");
// This is just a subset JSON data for this example
$json = '[{"timestamp":1367452800,"localTimestamp":1367452800,"issueTimestamp":1367452800,"fadedRating":0,"solidRating":0,"swell":{"minBreakingHeight":0,"absMinBreakingHeight":0,"maxBreakingHeight":0,"absMaxBreakingHeight":0,"unit":"ft","components":{"combined":{"height":2.5,"period":4,"direction":159.26,"compassDirection":"NNW"},"primary":{"height":1.9,"period":4,"direction":158.68,"compassDirection":"NNW"},"secondary":{"height":1.4,"period":5,"direction":255.73,"compassDirection":"ENE"}}},"wind":{"speed":8,"direction":182,"compassDirection":"N","chill":34,"gusts":13,"unit":"mph"},"condition":{"pressure":1024,"temperature":41,"weather":"10","unitPressure":"mb","unit":"f"},"charts":{"swell":"http:\/\/chart-1-us.msw.ms\/wave\/750\/1-1367452800-1.gif","period":"http:\/\/chart-1-us.msw.ms\/wave\/750\/1-1367452800-2.gif","wind":"http:\/\/chart-1-us.msw.ms\/gfs\/750\/1-1367452800-4.gif","pressure":"http:\/\/chart-1-us.msw.ms\/gfs\/750\/1-1367452800-3.gif","sst":"http:\/\/chart-1-us.msw.ms\/sst\/750\/1-1367452800-10.gif"}}]';
// Decode the JSON data into a PHP array using 'true'
// as 2nd argument of the json_decode function
$data = json_decode($json, true);
// Iterate each of the records and access the data as needed
foreach ($data as $record) {
echo "Timestamp: {$record['timestamp']}\n";
echo "Wind speed: {$record['wind']['speed']}\n";
echo "Temperature: {$record['condition']['temperature']}\n";
}
Output:
Timestamp: 1367452800
Wind speed: 8
Temperature: 41

Related

Pull nested JSON data using foreach loop in php

I want to pull data from below JSON format using PHP (foreach loop).
User detail is correspondence to house detail and house detail correspondence to individual meter reading.
I want to show Username, Device_No and all meter_detail field. Please help me out.
{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}
You need to convert the JSON to an array by using json_decode(). Then a couple of foreach loops would do work for you:
<?php
$json = '{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}';
$input = json_decode($json, true);
echo 'Username: '.$input['Username'].'<br>';
foreach ($input['Houses_list'] as $device){
echo '<br>Device No: '.$device['Device_No'].'<br>';
foreach ($device['meter_detail'] as $metrics){
echo '<table style="border: 1px solid black">';
foreach ($metrics as $key => $metric){
echo '<tr><td>'.$key.'</td><td>'.$metric.'</td></tr>';
}
echo '</table>';
}
}
?>
Output:

I have 2 tables ( unit , user ) each user can have many units, I am trying to return each user with it all units as json , using laravel

I am trying to do this:
$unitsPayments = Unit::leftJoin('uf_user', 'uf_unit.owner', '=', 'uf_user.id')
->select('uf_unit.code','uf_user.display_name','uf_unit.neighborhood',
'uf_unit.id AS unit_id','uf_unit.owner AS unit_owner')->get();
but it return the data separated like this.
I need to have first user and all it unit inside it
so at the end I will only have 2 nodes for users and each node will have 2 unit nodes
This is current JSON:
[
{
"code": "121",
"display_name": "zal",
"neighborhood": "wan",
"unit_id": 49,
"unit_owner": 17
},
{
"code": "47",
"display_name": "Ahmad",
"neighborhood": "aim",
"unit_id": 63,
"unit_owner": 2
},
{
"code": "21",
"display_name": "Ahmad",
"neighborhood": "wan",
"unit_id": 64,
"unit_owner": 2
},
{
"code": "102",
"display_name": "zal",
"neighborhood": "war",
"unit_id": 65,
"unit_owner": 17
}
]
and this is how I need the data to look like:
[{
"display_name": "zal",
"unit_owner": 17,
"units": {
"code": "102",
"neighborhood": "war",
"unit_id": 65
} {
"code": "121",
"neighborhood": "wan",
"unit_id": 49
}
},
{
"display_name": "Ahmad",
"unit_owner": 2,
"units": {
"code": "47",
"neighborhood": "aim",
"unit_id": 63,
} {
"code": "21",
"neighborhood": "wan",
"unit_id": 64,
}
}
]
You really should set up proper relationships using Eloquent: https://laravel.com/docs/5.5/eloquent-relationships
Your code will look like this:
$unitsPayments = User::with('units')->get();
And in User class:
class User extends Model {
public function units(){
return $this->hasMany(Unit::class, 'owner');
}
}

json file to php array. using json_decode gives null

I have the php file
<?php
$str = '{
"champions": [{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125.0,
}
}, {
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550.0,
}
}],
"matches": [{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
}, {"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}]
}';
$array = json_decode($str,true);// read string to array (true means array, false means object)
var_dump($array);
$champions = $array["champions"];
var_dump($champions);
which outputs null for both var_dumps. What is my mistake? Thanks. Is it maybe a problem that there are square brakets in the json snippet?
You have errors in your JSON.
Remove , in the end of [champions][stats] arrays.
please remove comma separation from every last element of champions->stats like below then do decode
{
"champions": [
{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125
}
},
{
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550
}
}
],
"matches": [
{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
},
{
"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}
]
}

Amchart dataLoader to have drilldown dynamically

Based on this tutorial https://www.amcharts.com/kbase/using-data-loader-to-connect-charts-to-mysql-data-base/, I am able to load the data by calling a php page using dataLoader into this kind of chart https://www.amcharts.com/demos/combined-bullet-column-line-chart/
My requirement:
When click on the column in the chart, it needs to call the another php file to fetch data with a different query based on the selection in the chart (that will be used as a where condition in query).
I tried something with the below code, but nothing works
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataDateFormat": "MM-YYYY",
"precision": 2,
"valueAxes": [{
"id": "v1",
"title": "Average",
"position": "left",
"autoGridCount": false,
"labelFunction": function(value) {
return Math.round(value) ;
}
}, {
"id": "v2",
"title": "Maximum",
"gridAlpha": 0,
"position": "right",
"autoGridCount": false
}],
"graphs": [{
"id": "g3",
"valueAxis": "v1",
"lineColor": "#e1ede9",
"fillColors": "#e1ede9",
"fillAlphas": 1,
"type": "column",
"title": "Actual Average",
"valueField": "Average",
"clustered": false,
"columnWidth": 12,
"legendValueText": "[[value]]",
"balloonText": "[[title]]<br /><b style='font-size: 130%'>[[value]]</b>"
}, {
"id": "g4",
"valueAxis": "v1",
"lineColor": "#62cf73",
"fillColors": "#62cf73",
"fillAlphas": 1,
"type": "column",
"title": "Actual Maximum",
"valueField":"Maximum",
"clustered": false,
"columnWidth":8,
"legendValueText": "[[value]]",
"balloonText": "[[title]]<br /><b style='font-size: 130%'>[[value]]</b>"
}, {
"id": "g1",
"valueAxis": "v2",
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#FFFFFF",
"bulletSize": 5,
"hideBulletsCount": 50,
"lineThickness": 2,
"lineColor": "#20acd4",
"type": "smoothedLine",
"title": "Target Average",
"useLineColorForBulletBorder": true,
"valueField": "Average",
"balloonText": "[[title]]<br /><b style='font-size: 130%'>[[value]]</b>"
}, {
"id": "g2",
"valueAxis": "v2",
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#FFFFFF",
"bulletSize": 5,
"hideBulletsCount": 50,
"lineThickness": 2,
"lineColor": "#e1ede9",
"type": "smoothedLine",
"dashLength": 5,
"title": "Target Maximum",
"useLineColorForBulletBorder": true,
"valueField": "Maximum",
"balloonText": "[[title]]<br /><b style='font-size: 130%'>[[value]]</b>"
}],
"chartScrollbar": {
"graph": "g1",
"oppositeAxis": false,
"offset": 30,
"scrollbarHeight": 50,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount": true,
"color": "#AAAAAA"
},
"chartCursor": {
"pan": true,
"valueLineEnabled": true,
"valueLineBalloonEnabled": true,
"cursorAlpha": 0,
"valueLineAlpha": 0.2
},
"categoryField": "Month",
"categoryAxis": {
"parseDates": true,
"dashLength":1,
"minorGridEnabled": true
},
"legend": {
"useGraphSettings": true,
"position": "top"
},
"balloon": {
"borderThickness": 1,
"shadowAlpha": 0
},
"export": {
"enabled": true
},
//"dataProvider":[{"Month":"01-2016","Average":43.63888889,"Maximum":50.06222222,"Province":"Riyadh"},{"Month":"02-2016","Average":46.11888889,"Maximum":52.78222222,"Province":"Eastern Province"},{"Month":"03-2016","Average":48.33740741,"Maximum":49.78555556,"Province":"Eastern Province"},{"Month":"04-2016","Average":39.37629630,"Maximum":41.25111111,"Province":"Eastern Province"},{"Month":"05-2016","Average":43.98481481,"Maximum":54.25000000,"Province":"Eastern Province"},{"Month":"06-2016","Average":49.68888889,"Maximum":71.53777778,"Province":"Riyadh"},{"Month":"07-2016","Average":39.92333333,"Maximum":44.52111111,"Province":"Eastern Province"},{"Month":"08-2016","Average":48.72370370,"Maximum":58.98222222,"Province":"Makkah"},{"Month":"09-2016","Average":34.18370370,"Maximum":43.88111111,"Province":"Makkah"},{"Month":"10-2016","Average":48.77962963,"Maximum":63.22333333,"Province":"Makkah"}]
"dataLoader": {"url": "bed-turnover.php"}
});
chart.addListener("clickGraphItem", function (event) {
// let's look if the clicked graph item had any subdata to drill-down into
// wow it has!
// let's set that as chart's
//chart.dataLoader.loadFile("bed-turnover-drill-province.php");
// event.chart.dataLoader ={"url": "bed-turnover-drill-province.php"};
// event.chart.validateData();
chart.dataLoader = { url: "bed-turnover-drill-province.php"}
//chart.validateData();
};
});
Kindly help.
Regards
You have to call the dataLoader's loadData method after you change the URL to load from the new source:
chart.addListener("clickGraphItem", function (event) {
chart.dataLoader.url = "bed-turnover-drill-province.php";
chart.dataLoader.loadData();
};

Getting data out of a JSON API with PHP

Im having trouble extracting data from a API, i would like to use for a school project..
The link to the API i here
Or here's a sample of the API output
{
"help": "http://www.odaa.dk/api/3/action/help_show?name=datastore_search",
"success": true,
"result": {
"resource_id": "2a82a145-0195-4081-a13c-b0e587e9b89c",
"fields": [
{
"type": "int4",
"id": "_id"
},
{
"type": "text",
"id": "date"
},
{
"type": "text",
"id": "garageCode"
},
{
"type": "int4",
"id": "totalSpaces"
},
{
"type": "int4",
"id": "vehicleCount"
}
],
"records": [
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 62,
"_id": 1,
"totalSpaces": 65,
"garageCode": "NORREPORT"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 512,
"_id": 2,
"totalSpaces": 512,
"garageCode": "SKOLEBAKKEN"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 236,
"_id": 3,
"totalSpaces": 1240,
"garageCode": "SCANDCENTER"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 40,
"_id": 4,
"totalSpaces": 953,
"garageCode": "BRUUNS"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 2932,
"_id": 5,
"totalSpaces": 142,
"garageCode": "BUSGADEHUSET"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 18,
"_id": 6,
"totalSpaces": 383,
"garageCode": "MAGASIN"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 3,
"_id": 7,
"totalSpaces": 210,
"garageCode": "KALKVAERKSVEJ"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 255,
"_id": 8,
"totalSpaces": 700,
"garageCode": "SALLING"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 0,
"_id": 9,
"totalSpaces": 0,
"garageCode": "DOKK1"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 34,
"_id": 10,
"totalSpaces": 449,
"garageCode": "Navitas"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 105,
"_id": 11,
"totalSpaces": 105,
"garageCode": "NewBusgadehuset"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 9,
"_id": 12,
"totalSpaces": 319,
"garageCode": "Urban Level 1"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 15,
"_id": 13,
"totalSpaces": 654,
"garageCode": "Urban Level 2+3"
}
],
"_links": {
"start": "/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c",
"next": "/api/action/datastore_search?offset=100&resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c"
},
"total": 13
}
}
I would like to extract the cells called "vehicleCount" and "_id", but i seems I can't figure out how to do it :(
$json = file_get_contents('http://www.odaa.dk/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c');
$json = json_decode($json);
echo $json->fields->_id;
I have tried many different ways, but now loss of ideas and its 4 o'clock in the morning, so hopefully someone can help me.
if you want to extract the cells vehicleCount and _id
This is my solution for you:
<?php
$json = file_get_contents('http://www.odaa.dk/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c');
$json = json_decode($json);
foreach ($json->result->records as $val) {
echo "_id = " .$val->_id . " vehicleCount = " . $val->vehicleCount . "<br>";
}
?>
$json->result->records[0]->_id

Categories