Read Json with features fields - php

I have the following problem.
I am trying to read a Json file but I am not getting the desired result. I have the following data.
I would like to read the features and there is a mistake in finding out somewhere.
I get the error message when reading out:
Warning: Illegal string offset 'features'
Output
Array
(
[objectIdFieldName] => OBJECTID
[uniqueIdField] => Array
(
[name] => OBJECTID
[isSystemMaintained] => 1
)
[globalIdFieldName] =>
[geometryProperties] => Array
(
[shapeAreaFieldName] => Shape__Area
[shapeLengthFieldName] => Shape__Length
[units] => esriMeters
)
[geometryType] => esriGeometryPolygon
[spatialReference] => Array
(
[wkid] => 4326
[latestWkid] => 4326
)
[fields] => Array
(
[0] => Array
(
[name] => GEN
[type] => esriFieldTypeString
[alias] => GEN
[sqlType] => sqlTypeOther
[length] => 33
[domain] =>
[defaultValue] =>
)
[1] => Array
(
[name] => cases
[type] => esriFieldTypeInteger
[alias] => Anzahl Fälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
[2] => Array
(
[name] => deaths
[type] => esriFieldTypeInteger
[alias] => Anzahl Todesfälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
)
[features] => Array
(
[0] => Array
(
[attributes] => Array
(
[GEN] => Celle
[cases] => 220
[deaths] => 15
)
...........
My Code
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
echo $row['features']->$row['attributes']->$row['GEN'];
}
Where am I wrong in reading?
It only has to be read what is in parentheses right?
So actually features-> attributes-> Gen to get the GEN query

Let's try change to this.
foreach($data as $row){
echo $row['features'][0]['attributes']['GEN'];
}

Sorry this is my fault when seem does'nt read clearly your question.
With GEN attribute you don't use loop to get this value.
If you wanna get GEN only your code should be that.
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = (array) json_decode($json, true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
echo $data['features']['attributes']['GEN'];
// foreach($data as $row){
// echo $row['features']->$row['attributes']->$row['GEN'];
// }

Related

Retrieve a value from JSON Object using PHP (Shiprocket API)

I am getting below json data thru Shiprocket API. Now I want to extract value of below variables in PHP code from this json.
I have tried to use json_decode but it did not work and show null value:
$data = json_decode($json);
$sr_status = $data['shipment_status'];
Please suggest the code to retrieve below variables value.
shipment_status , awb_code , courier_company_id
Array
(
[0] => stdClass Object
(
[tracking_data] => stdClass Object
(
[track_status] => 1
[shipment_status] => 7
[shipment_track] => Array
(
[0] => stdClass Object
(
[id] => 180339484
[awb_code] => 11150911492
[courier_company_id] => 55
[shipment_id] => 1711169662
[order_id] => 233223781187
[pickup_date] => 2023-01-11 03:02:00
[delivered_date] => 2023-01-16 12:22:00
[weight] => 0.25
[packages] => 1
[current_status] => Delivered
[delivered_to] => Solapur
[destination] => Solapur
[consignee_name] => ABC
[origin] => Ludhiana
[courier_agent_details] =>
[edd] =>
)
)
[shipment_track_activities] => Array
(
[0] => stdClass Object
(
[date] => 2023-01-16 12:22:00
[status] => 000-T-DL
[activity] => SHIPMENT DELIVERED
[location] => SOLAPUR
[sr-status] => 7
[sr-status-label] => DELIVERED
)
[1] => stdClass Object
(
[date] => 2023-01-16 11:34:00
[status] => 002-S-UD
[activity] => SHIPMENT OUTSCAN
[location] => SOLAPUR
[sr-status] => 17
[sr-status-label] => OUT FOR DELIVERY
)
)
[track_url] => https://shiprocket.co//tracking/11150911492
[etd] => 2023-01-14 17:02:00
[qc_response] => stdClass Object
(
[qc_image] =>
[qc_failed_reason] =>
)
)
)
)
you can try this:
$array = ...; // Your array here
$data= json_decode($array);
$shipment_status = $data[0]->tracking_data->shipment_status;
$awb_code = $data[0]->tracking_data->shipment_track[0]->awb_code;
$courier_company_id = $data[0]->tracking_data->shipment_track[0]->courier_company_id;
Or use $data = json_decode($json,true); which return an array where you can use
foreach($data as $val) {
$shipment_status = $val['tracking_data']['shipment_status'];
foreach ($val['shipment_track'] as $value) {
$awb_code = $value['awb_code'];
$courier_company_id = $value['courier_company_id'];
}
}

JSON Decode save array

I am able to receive the following JSON data with the following PHP code:
$json = file_get_contents('https://xxxx');
$data = json_decode($json,true);
$forex = $data['items'];
echo "<pre>";
print_r($forex);
exit;
This gives me the following JSON data:
Array
(
[0] => Array
(
[new] =>
[data] => Array
(
[direction] => 1
[pip] => 0
[exchange] => FOREX
[symbol] => USDCHF
[interval] => 15
[pattern] => Resistance
[complete] =>
[identified] => 2020-02-26T14:45:00.000Z
[age] => 0
[length] => 259
[found] => 2020-02-26T14:45:56.381Z
[result_type] => KeyLevel
[result_uid] => 642525551
[prediction_price_from] => 0
[prediction_price_to] => 0
[group_name] => FX Majors
[symbol_name] => USDCHF
[symbol_id] => 0
[analysis_text] => Approaching Resistance level of 0.9800 identified at 2/26 14:45. This pattern is still in the process of forming. Possible bullish price movement towards the resistance 0.9800 within the next 15 hours.
[expires_at] => 2020-02-27T05:48:36.701Z
)
[links] => Array
(
[0] => Array
(
[rel] => detail
[href] => https://xxxx
)
[1] => Array
(
[rel] => analysis
[href] => https://xxxx
)
[2] => Array
(
[rel] => chart-xs
[href] => https://xxxx
)
[3] => Array
(
[rel] => chart-sm
[href] => https://xxxx
)
[4] => Array
(
[rel] => chart-md
[href] => https://xxxx
)
[5] => Array
(
[rel] => chart-lg
[href] => https://xxxx
)
[6] => Array
(
[rel] => icon-arrow
[href] => https://xxxx
)
)
)
What I am trying to do is to save the information into my MySQL database, however I am unable to get the data displayed even by testing to echo the data:
foreach($forex as $info) {
echo $info->symbol . '<br>';
}
Anyone with a possible solution for me to save the data or even enable me to display the data for each Array (Example: symbol, pattern, link chart-md).
Below the commented code:
//Save json text into variable $json
$json = file_get_contents('https://xxxx');
//Convert json into PHP array
$data = json_decode($json,true);
//Set $forex as $data['items'];
$forex = $data['items'];
//Print
echo "<pre>";
print_r($forex);
exit;
$forex is a PHP array variable (not a JSON string).
You could save your data into MySQL VARCHAR[Length] field using json string variable $json instead of PHP array $forex.
When you need to get the data from DB and display it, you could get JSON data from MySQL and convert it from JSON to Array using PHP json_decode($json,true).
If you want to use a value into a PHP array, use $info["symbol"] instead of $info->symbol

How to get the value from a specific key in an array?

I have the following array:
Array (
[result] => Array (
[id] => 58fba3ebf4
[type] => A
[name] => ser.domain.com
[content] => 192.168.100.1
[proxiable] =>
[proxied] =>
[ttl] => 1
[priority] => 10
[locked] =>
[zone_id] => eb0d86828e3ac837c
[zone_name] => domain.com
[modified_on] => 2018-07-06T06:37:14.069598Z
[created_on] => 2018-07-06T06:37:14.069598Z
[meta] => Array (
[auto_added] =>
[managed_by_apps] =>
[managed_by_argo_tunnel] =>
)
)
[success] => 1
[errors] => Array ( )
[messages] => Array ( )
)
How can I just get the value from id?
$data =json_decode($response);
$id = $data->result->id;
Assuming your payload from the request was $response.
You already have a multi-dimensional array so just try like this
echo $arrays['result']['id']; // this will return id
echo $arrays['result']['type']; // this will return type
Here is solution
// $result_array() is your reponse from curl PHP
$data = $result_array();
$id = $data['result']['id'];

PHP efficiently accessing values in a JSON array on different levels

Working on a personal project that will pull results from an API with full details of each pokemon.
So far I got the contents of the URL and returned the results into a JSON array format.
At the moment I am stuck on trying to retrieve results for[stats] inside from the array in an efficient manner.
private function getGenOnePokemon()
{
// the url of the api
$url = $this->baseUrl;
//get the contents of $url var and decode it into a json array
$json = file_get_contents($url , true);
$pokemon = json_decode($json, true, JSON_UNESCAPED_UNICODE);
// array output of pokemon
echo '<pre> ';
print_r($pokemon);
echo'</pre>';
//echo out value as speed
foreach($pokemon['results'][0] as $happy)
{
echo $happy['name'] . '<br />';
}
// echo base_stat value for speed with value of 90
echo $pokemon['stats'][0]['base_stat'];
}
However I do not seem to get anywhere much printing values/keys as I need to add something else to have full access to the values?
Would prefer not to directly access results, like I am doing with base_stat as plan on using this logic to pass into HTML View layer later.
Example of print_r dump (not full dump as really long) Full example: https://pokeapi.co/api/v2/pokemon/pikachu
Array
(
[forms] => Array
(
[0] => Array
(
[url] => https://pokeapi.co/api/v2/pokemon-form/25/
[name] => pikachu
)
)
[abilities] => Array
(
[0] => Array
(
[slot] => 3
[is_hidden] => 1
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/31/
[name] => lightning-rod
)
)
[1] => Array
(
[slot] => 1
[is_hidden] =>
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/9/
[name] => static
)
)
)
[stats] => Array
(
[0] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/6/
[name] => speed
)
[effort] => 2
[base_stat] => 90
)
[1] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/5/
[name] => special-defense
)
[effort] => 0
[base_stat] => 50
)
[2] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/4/
[name] => special-attack
)
[effort] => 0
[base_stat] => 50
)
[3] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/3/
[name] => defense
)
[effort] => 0
[base_stat] => 40
)
[4] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/2/
[name] => attack
)
[effort] => 0
[base_stat] => 55
)
[5] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/1/
[name] => hp
)
[effort] => 0
[base_stat] => 35
)
)
Any advice on how to access the data using foreach or other tips greatly appreciated. Thank you!
PHP has a specific function designed to target columnar data from arrays. It is called array_column()
If you want to isolate all of the name elements inside the forms subarray, use this:
$names=array_column($pokemon['forms'],'name');
If you want to isolate all of the base_stat elements inside of the stats subarray, use this:
$base_stats=array_column($pokemon['stats'],'base_stat');
Now you will have $names and $base_stats which are single-dimensional arrays by which you can perform additional processes or return from the function. Clean, intuitive, and simple.
Your $pokemon array doesn't contain a results field. There's only an forms field. So you should iterate over forms to print the names of the forms.
foreach($pokemon['forms'] as $happy) {
echo $happy['name'] . '<br />';
}
You could do the same thing with the stats
foreach($pokemon['stats'] as $stat) {
$base_stat = $stat['base_stat'];
// ...
}

How to fetch specific fields from array using file_get_contents

I want to fetch player fields:
e.g id,name,tag,plat etc
I have this type of data:
stdClass Object
(
[player] => stdClass Object
(
[id] => 179203896
[game] => bf4
[plat] => pc
[name] => HeLLTiMe
[tag] => DK
[dateCheck] => 1391437377733
[dateUpdate] => 1391437377733
[dateCreate] => 1386696304438
[lastDay] => 20140117
[country] =>
[countryName] =>
[rank] => stdClass Object
(
[nr] => 73
[imgLarge] => bf4/ranks/r73.png
[img] => r73
[name] => Chief Warrant Officer Five III
[needed] => 4920000
[next] => stdClass Object
(
[nr] => 74
[img] => r74
[name] => Chief Warrant Officer Five IV
[needed] => 5030000
[curr] => 5022060
[relNeeded] => 110000
[relCurr] => 102060
[relProg] => 92.781818181818
)
)
[score] => 5025100
[timePlayed] => 862027
[uId] => 2832659368608119092
[uName] => HeLLTiMe
[uGava] => 0b8b00021ebfb32414e5a6051c2c9a40
[udCreate] => 1328606863000
[blPlayer] => http://battlelog.battlefield.com/bf4/soldier/HeLLTiMe/stats/179203896/pc/
[blUser] => http://battlelog.battlefield.com/bf4/user/HeLLTiMe/
[editable] =>
[viewable] => 1
[adminable] =>
[linked] =>
)
[stats] => stdClass Object
(
[reset] => stdClass Object
(
[lastReset] => 0
[score] => 0
[timePlayed] => 0
[timePlayedSinceLastReset] => 0
[kills] => 0
[deaths] => 0
[shotsFired] => 0
[shotsHit] => 0
[numLosses] => 0
[numWins] => 0
)
How can I fetch this data?
Here is my code:
<?php
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
$data = json_decode($json);
echo "<pre>";
print_r($data);
?>
to get the name you should do this:
echo $data->player->name;
You need this because you have a stdClass Object
You can also change the out to just a array, you have to change this:
$data = json_decode($json);
to this:
$data = json_decode($json, true);
When you make this chagne you can get the value by this:
echo $data['player']['name'];
Edit
Below you can see the example, this works for me with no error.
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
echo 'Using stdClass Object option<br>';
$data = json_decode($json);
echo $data->player->name;
echo '<br><br>Using Array option<br>';
$data = json_decode($json, true);
echo $data['player']['name'];
exit;
$result = array();
$result['name'] = $data->Player->name
var_dump($result);
Not sure what do you mean by fetch the data as already fetched it but if you ask how to access the fields you can do it like this.
print_r($data->player->name);

Categories