Getting php array value - php

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

Related

Getting a specific value from a json response

I have this code
$client = json_decode($client);
echo "<pre>";
print_r($client);
which produces there
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Jojohn#doe.com
[email_verified_at] =>
[password] => $2y$10$pAvJ9/K7ZPOqw10WhfmToumK0TY1XihY8M9uAEEs4GkHZr4LdGc4e
[remember_token] =>
[created_at] => 2020-07-29 21:08:02
[updated_at] =>
[userid] => 2
[account_rep] => 3
)
)
My question is how do I get the value of name and account_rep I tried
echo $client['0']['object']['name'];
but that does not work it just throws an error
Cannot use object of type stdClass as array
json_decode($variable), is used to decode or convert a JSON object to a PHP object.
So you could do this as $client['0'] is an object.
echo $client['0']->name;
But I'd say you should rather convert the json object to associative array instead of PHP object by passing TRUE to as an argument to the json_decode. When TRUE, returned objects get converted into associative arrays.
$client = json_decode($client, true);
Now $client is
Array
(
[0] => Array
(
[id] => 1
[name] => Jojohn#doe.com
[email_verified_at] =>
[password] => $2y$10$pAvJ9/K7ZPOqw10WhfmToumK0TY1XihY8M9uAEEs4GkHZr4LdGc4e
[remember_token] =>
[created_at] => 2020-07-29 21:08:02
[updated_at] =>
[userid] => 2
[account_rep] => 3
)
)
Now you could simply do
echo $client[0]['name'];

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

Get stdClass Object value

I'm trying to get a value from stdClass Object array with no success.
Here is the code I'm running:
$myjson =
'{"2":{"label":"","value":"","type":null,"validation":null,"required":null},
"6":{"label":"files","value":"getThisValue","type":"file0","validation":null,"required":null},
"3":{"label":"location","value":"val3","type":"hidden","validation":"","required":"0"}
,"0":{"custom3":"zz","value":"","label":""},"1":{"custom3":"zz","value":"","label":""}
}';
$json = json_decode($myjson);
echo $json[6]->'value';
This is doesn't work, If I Print_r the JSON after decoding (print_r($json)), the array will look like this:
stdClass Object (
[2] => stdClass Object ( [label] => [value] =>
[type] => [validation] => [required] => )
[6] => stdClass Object (
[label] => files [value] => getThisValue [type] => file0 [validation]
=> [required] => )
[3] => stdClass Object ( [label] => location [value] => val3 [type] => hidden [validation] => [required] => 0 )
[0]
=> stdClass Object ( [custom3] => zz [value] => [label] => )
[1] => stdClass Object ( [custom3] => zz [value] => [label] => ) )
I need the Value: getThisValue. Any idea how I can get it? (I tried many options with no success).
Try echo $json["6"]["value"];
But for this you have to use json_decode($myjson, true); true, to get an array.
Because it's going to be two arrays inside each other and not an object you have to use 2 brackets.
You can't use a std object as an array. But in order to get your code working just add this line:
$json = get_object_vars($json);
After this you can access it like this:
echo $json[6]->value;
You could add true to your json_decode, like this: json_decode($myjson, true);, it will now convert your json object to an associative array.
And from there on you can get to the value you want by requesting the key, just like other arrays.
$newArray = json_decode($myjson, true);
echo $newArray['something'];
If you want to get the values from stdObject without converting it to array, you can do it like this:
echo $json->{'6'}->value
You can use the {'property_name'} notation to get a value of a class property with non-standard name (for ex. a number).

How can I loop through a stdObject's array without raising PHP notices/warnings?

I have the following stdObject obtained thru cURL / json_decode():
stdClass Object
(
[response] => stdClass Object
(
[status] => OK
[num_elements] => 1030
[start_element] => 0
[results] => stdClass Object
(
[publisher] => stdClass Object
(
[num_elements] => 1030
[results] => Array
(
[0] => stdClass Object
(
[id] => 1234
[weight] => 4444
[name] => Pub 1
[member_id] => 1
[state] => active
[code] =>
)
[1] => stdClass Object
(
[id] => 1235
[weight] => 4444
[name] => Pub 2
[member_id] => 2
[state] => active
[code] =>
)
)
)
)
[dbg_info] => stdClass Object
(
[instance] => instance1.server.com
[slave_hit] => 1
[db] => db1.server.com
[reads] => 3
[read_limit] => 100
[read_limit_seconds] => 60
[writes] => 0
[write_limit] => 60
[write_limit_seconds] => 60
[awesomesauce_cache_used] =>
[count_cache_used] =>
[warnings] => Array
(
)
[time] => 70.440053939819
[start_microtime] => 1380833763.4083
[version] => 1.14
[slave_lag] => 0
[member_last_modified_age] => 2083072
)
)
)
I'm looping through it in order to obtain each result's ID:
foreach ($result->response->results->publisher->results as $object) {
$publishers .= $object->id.",";
}
And although the code is working fine, PHP is rising the following notices/warnings:
PHP Notice: Trying to get property of non-object in /var/www/vhosts/domain.net/script.php on line 1
PHP Notice: Trying to get property of non-object in /var/www/vhosts/domain.net/script.php on line 1
PHP Warning: Invalid argument supplied for foreach() in /var/www/vhosts/domain.net/script.php on line 1
Any ideas? Thanks in advance!
Is it possible you have set the second parameter $assoc in json_decode() to true? Like this:
$result = json_decode($json_from_curl, true);
Thereby, getting back $result with all stdClass Objects converted to associative array.
EDIT:
If the $result you are getting is indeed an associative array, then we should treat it as such. Try replacing your foreach with this:
foreach ($result['response']['results']['publisher']['results'] as $arr) {
$publishers .= $arr['id'] . ",";
}
EDIT2:
From my own testing based on your code, everything should be working correctly. The notices/warnings should not occur. Perhaps some other code not shown in your question is causing it.

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