How to decode json string into half array/ half object? - php

I have the following json string
$str = '{"icwsCallQueue":{"1002598152":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259815260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"},"1002598162":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259816260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"}}}';
If I decode it using json_decode($str)
I get the following
stdClass Object
(
[icwsCallQueue] => stdClass Object
(
[1002598152] => stdClass Object
(
[AccoRDI_account_id] =>
[AccoRDI_mid] =>
[Eic_CallDirection] => O
[Eic_CallIdKey] => 100259815260150624
[Eic_CallState] => Disconnected
[Eic_ConferenceId] =>
[Eic_ConferenceMembers] =>
[Eic_ImmediateAccess] => 1
[Eic_LocalName] => Full Name
[Eic_LocalUserId] => username
[Eic_MonitorsCombinedCount] => 0
[Eic_Muted] =>
[Eic_ObjectType] => Call
[Eic_ParentConferenceId] =>
[Eic_RemoteAddress] => 307
[Eic_RemoteName] => username-test
[Eic_State] => I
)
[1002598162] => stdClass Object
(
[AccoRDI_account_id] =>
[AccoRDI_mid] =>
[Eic_CallDirection] => O
[Eic_CallIdKey] => 100259816260150624
[Eic_CallState] => Disconnected
[Eic_ConferenceId] =>
[Eic_ConferenceMembers] =>
[Eic_ImmediateAccess] => 1
[Eic_LocalName] => Full Name
[Eic_LocalUserId] => username
[Eic_MonitorsCombinedCount] => 0
[Eic_Muted] =>
[Eic_ObjectType] => Call
[Eic_ParentConferenceId] =>
[Eic_RemoteAddress] => 307
[Eic_RemoteName] => username-test
[Eic_State] => I
)
)
)
The problem with this is that I can't access a property with only an integer. I can't do this $icwsCallQueue->100259152->Eic_State
so what I need to do some how is convert my decoded string to something like this
stdClass Object
(
[icwsCallQueue] => Array
(
[1002598152] => stdClass Object
(
[AccoRDI_account_id] =>
[AccoRDI_mid] =>
[Eic_CallDirection] => O
[Eic_CallIdKey] => 100259815260150624
[Eic_CallState] => Disconnected
[Eic_ConferenceId] =>
[Eic_ConferenceMembers] =>
[Eic_ImmediateAccess] => 1
[Eic_LocalName] => Full Name
[Eic_LocalUserId] => username
[Eic_MonitorsCombinedCount] => 0
[Eic_Muted] =>
[Eic_ObjectType] => Call
[Eic_ParentConferenceId] =>
[Eic_RemoteAddress] => 307
[Eic_RemoteName] => username-test
[Eic_State] => I
)
[1002598162] => stdClass Object
(
[AccoRDI_account_id] =>
[AccoRDI_mid] =>
[Eic_CallDirection] => O
[Eic_CallIdKey] => 100259816260150624
[Eic_CallState] => Disconnected
[Eic_ConferenceId] =>
[Eic_ConferenceMembers] =>
[Eic_ImmediateAccess] => 1
[Eic_LocalName] => Full Name
[Eic_LocalUserId] => username
[Eic_MonitorsCombinedCount] => 0
[Eic_Muted] =>
[Eic_ObjectType] => Call
[Eic_ParentConferenceId] =>
[Eic_RemoteAddress] => 307
[Eic_RemoteName] => username-test
[Eic_State] => I
)
)
)
so I can access the records like this $icwsCallQueue['100259152']->Eic_State
on the other hand if I decoded the string like this json_decode($str, true) everything will be presented as array which is not what am I looking for.
Any idea on how to decode the string with array when array must be used and object when array can be avoided?

You can cast array to stdclass and stdclass to array when needed.
First of all json_decode($str, true) to get the associative version of the data.
Then iterate through the most inner parts of the data and cast arrays back to objects again. Now it's possible to use stdclass properties as accessors.
$str = '{"icwsCallQueue":{"1002598152":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259815260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"},"1002598162":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259816260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"}}}';
$json = json_decode($str, true);
foreach($json["icwsCallQueue"] as $key => $element) {
$json["icwsCallQueue"][$key] = (object)$element;
}
var_dump($json["icwsCallQueue"]['1002598152']->Eic_CallIdKey);
var_dump($json["icwsCallQueue"]['1002598162']->Eic_CallIdKey);
There was another and simpler solution but I couldn't make it work. That's why I have to iterate all the array.
$str = '{"icwsCallQueue":{"1002598152":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259815260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"},"1002598162":{"AccoRDI_account_id":"","AccoRDI_mid":"","Eic_CallDirection":"O","Eic_CallIdKey":"100259816260150624","Eic_CallState":"Disconnected","Eic_ConferenceId":"","Eic_ConferenceMembers":"","Eic_ImmediateAccess":"1","Eic_LocalName":"Full Name","Eic_LocalUserId":"username","Eic_MonitorsCombinedCount":"0","Eic_Muted":"","Eic_ObjectType":"Call","Eic_ParentConferenceId":"","Eic_RemoteAddress":"307","Eic_RemoteName":"username-test","Eic_State":"I"}}}';
$json = json_decode($str);
$jsonArray = (array)$json->icwsCallQueue;
var_dump($jsonArray["1002598152"]);
//PHP Notice: Undefined offset: 1002598152 in
Looks like PHP does not cast to array properly with integer keys. Or there is something I am missing here.
The rest is up to your imagination.

Related

Read Json with features fields

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'];
// }

Getting php array value

Hello i have quick question.
I have an array witch looks like that:
Array ( [id] => 311 [file] => [name] => Mobilny [minutes] => [connection_type] => [price] => [price_landline] => [price_mobile] => [prices] => [{"city_id":"304","months":"0","price":"1","minutes":"0"}] [link] => mobilny [page_id] => 3521 [hidden_number] => Y [position] => 0 [date] => 2016-07-26 [date_modify] => 2016-08-29 )
And this array has this column:
[prices] => [{"city_id":"304","months":"0","price":"1","minutes":"0"}]
My question is, is this value is treated like a string?
[{"city_id":"304","months":"0","price":"1","minutes":"0"}]
How can i access value from city_id? When i use $table[0]['prices'] i get following: [{"city_id":"304","months":"0","price":"1","minutes":"0"}] and i don't know how to get city_id from it.
You have JSON formatted value. Decode it using json_decode function.
//Decode JSON to object
$decoded = json_decode($table[0]['prices']);
$cityId = $decoded->city_id;
//Decode JSON to associative array
$decoded = json_decode($table[0]['prices'], true);
$cityId = $decoded['city_id'];

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);

Extracting data from this object/array? How to do it

Here is a snippet of the print off of $wp_scripts
WP_Scripts Object
(
[base_url] => http://*****
[content_url] => http://*****
[default_version] => 3.5.1
[in_footer] => Array
(
)
[concat] =>
[concat_version] =>
[do_concat] =>
[print_html] =>
[print_code] =>
[ext_handles] =>
[ext_version] =>
[default_dirs] => Array
(
[0] => /wp-admin/js/
[1] => /wp-includes/js/
)
[registered] => Array
(
[utils] => _WP_Dependency Object
(
[handle] => utils
[src] => /wp-includes/js/utils.min.js
[deps] => Array
(
)
How would i Extract some data, for example "/wp-includes/js/utils.min.js"??
Thanks
$wp_scripts->registered['utils']->src
Accessing object properties via ->
Accessing array elements via [/* String or integer here*/]
$object = new WP_Scripts;
$src = $object->registered['utils']->src;

Unable to access array element with json_decode

I have used json_decode to get an array from a JSON response:
$result = (json_decode($trends,true));
which gives me the following (I haven't included all of the EstablishmentDetail array results)
Array ( [FHRSEstablishment] => Array ( [Header] => Array ( [#text] => [ExtractDate] => 2012-05-28 [ItemCount] => 5 [ReturnCode] => Success ) [EstablishmentCollection] => Array ( [EstablishmentDetail] => Array ( [0] => Array ( [FHRSID] => 248659 [LocalAuthorityBusinessID] => INS/06/06179 [BusinessName] => Ancient Raj [BusinessType] => Restaurant/Cafe/Canteen [BusinessTypeID] => 1 [AddressLine1] => 26 North Lane, Canterbury, [PostCode] => CT2 7EE [RatingValue] => 3 [RatingKey] => fhrs_3_en-GB [RatingDate] => 2010-11-18 [LocalAuthorityCode] => 180 [LocalAuthorityName] => Canterbury City [Scores] => [SchemeType] => FHRS [Geocode] => )
which I thought I' be able to use a foreach to get to the BusinessName:
foreach ($result->FHRSEstablishment->EstablishmentCollection->EstablishmentDetail as $detail){
echo $detail['BusinessName'];
}
but I'm not getting any results.
The problem is that you're accessing your $result as an object:
$result->FHRSEstablishment
but when you're calling json_decode with the second parameter set to true, it's returning an associative array, which you should access as:
$result['FHRSEstablishment']['EstablishmentCollection'] //...
If you want to be able to access your $result with object notation, you should define it as:
$result = json_decode($trends) //without 2nd parameter = true

Categories