Unable to access array element with json_decode - php

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

Related

Returning multidimensional array value for PHP

I'm to return data from a provider and the array supplied looks like this :
Array
(
[result] => Array
(
[0] => Array
(
[problem_id.u_root_cause] =>
[number] => INC0000001
[short_description] => Unable to print
[u_alert_check] =>
[u_business_service] => Array
(
[display_value] => Printer
[link] => https://redacted/37bc8af837c3820ca7e3b15ec3990e1c
)
[assignment_group] => Array
(
[display_value] => Printer Support
[link] => https://redacted/b699595c37dac200a7e3b15ec3990eb1
)
[u_service_impact_duration] => 57 Minutes
[u_summary_notes] => Changed USB cable
[u_environment] => Production (PD)
[problem_id] =>
[priority] => 3 - P3
[u_business_services_impacted] =>
)
Now, I'm able to return most of the data like this,
foreach($data['result'] as $line){
echo $line['number'];
echo '<br>';
echo $line['short_description'];
}
The above returns the number and short_description from the array.
The trouble I have is how do I return u_business_service in the same line?
For acessing the multidimensional array you may use:
echo $line['u_business_service']['display_value'];
echo $line['u_business_service']['link'];

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

PHP: Displaying data from Bigcommerce API

I am trying to display the data from Bigcommerce through php when I run the Bigcommerce::getCategories() i getting a array of data like this:
[0] => Bigcommerce\Api\Resources\Category Object
(
[ignoreOnCreate:protected] => Array
(
[0] => id
[1] => parent_category_list
)
[ignoreOnUpdate:protected] => Array
(
[0] => id
[1] => parent_category_list
)
[fields:protected] => stdClass Object
(
[id] => 88
[parent_id] => 0
[name] => Dell
[description] =>
[sort_order] => 0
[page_title] =>
[meta_keywords] =>
[meta_description] =>
[layout_file] =>
[parent_category_list] => Array
(
[0] => 88
)
[image_file] =>
[is_visible] => 1
[search_keywords] =>
[url] => /dell/
)
[id:protected] => 88
[ignoreIfZero:protected] => Array
(
)
[fieldMap:protected] => Array
(
)
)
but when I try to pass this to JQuery so that I can display it using this statement: <?php echo json_encode($categories); ?> I am getting an array of empty objects, what is the right way to get the array of objects in Bigcommerce API? Thanks.
From the first line of your code:
[0] => Bigcommerce\Api\Resources\Category Object
You have an object, not an array. Try casting it to an array first:
$array = (array) $yourObject;

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 decode json string into half array/ half object?

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.

Categories