extract details from from string - php

I have a string in my database along with type varchar
{"available":"","bind":"0","hours":{"00:00":{"available":"","bind":"0","info":"","notes":"","price":"","promo":"","status":"none"}},"hours_definitions":[{"value":"00:00"}],"info":"","notes":"","price":"100","promo":"","status":"available"}
How do I extract the price from this?

That string is valid JSON data, so you all you need to do is decode to an array for PHP to read. Like so:
$data = json_decode($string);
$price = $data->price;
To force it to be an array instead of an object, pass true to the second argument of json_decode, like so:
$data = json_decode($string, true);
$price = $data['price'];

That looks like JSON to me, so the steps are really simple:
1. Use json_decode($response, true) to convert from JSON to an array.
2. Treat as a normal array.
As such, the following code should work fine for you
$info = json_decode($jsonCode, true);
$price = $info['price'];
And the price will be stored in $price, or just $info['price'] if you don't need another variable for it.
json_decode()'s second argument means that it will return associative arrays (like the one you have here) as an array, rather than an object. It's usually more useful that way, however you could always set it to false (or just leave it out, as false is the default).
See json_decode's PHP documentation page for more info on its arguments.

Related

How to get label data from JSON from file contents

$json = file_get_contents('module=API&method=Referrers.getReferrerType&format=json&period=day&date=yesterday&disableLink=1&idSite=3');
$data = json_decode($json,true);
json data:
[{"label":"Direct Entry","nb_uniq_visitors":526,"nb_visits":593,"nb_actions":768,"nb_users":0,"max_actions":32,"sum_visit_length":83153,"bounce_count":513,"nb_visits_converted":0,"segment":"referrerType==direct"},{"label":"Search Engines","nb_uniq_visitors":230,"nb_visits":235,"nb_actions":631,"nb_users":0,"max_actions":71,"sum_visit_length":52233,"bounce_count":150,"nb_visits_converted":0,"segment":"referrerType==search","idsubdatatable":2},{"label":"Websites","nb_uniq_visitors":7,"nb_visits":7,"nb_actions":20,"nb_users":0,"max_actions":5,"sum_visit_length":835,"bounce_count":1,"nb_visits_converted":0,"segment":"referrerType==website","idsubdatatable":3}]
I'm trying to display each label for the referrer type.
Direct Entry
Search Engines
Websites
$data[0]->label; doesn't work
$data->label; doesn't work
$data->label[0]; doesn't work
You passed true to the second parameter to json_decode(). That makes it return an associative array. Thus, you can simply use the data like this :
$data[0]["label"]
You can try this, as you're converting the json data to associative array (nested), by passing true into the 2nd argument of json_decode method:
$json = "[{\"label\":\"Direct Entry\",\"nb_uniq_visitors\":526,\"nb_visits\":593,\"nb_actions\":768,\"nb_users\":0,\"max_actions\":32,\"sum_visit_length\":83153,\"bounce_count\":513,\"nb_visits_converted\":0,\"segment\":\"referrerType==direct\"},{\"label\":\"Search Engines\",\"nb_uniq_visitors\":230,\"nb_visits\":235,\"nb_actions\":631,\"nb_users\":0,\"max_actions\":71,\"sum_visit_length\":52233,\"bounce_count\":150,\"nb_visits_converted\":0,\"segment\":\"referrerType==search\",\"idsubdatatable\":2},{\"label\":\"Websites\",\"nb_uniq_visitors\":7,\"nb_visits\":7,\"nb_actions\":20,\"nb_users\":0,\"max_actions\":5,\"sum_visit_length\":835,\"bounce_count\":1,\"nb_visits_converted\":0,\"segment\":\"referrerType==website\",\"idsubdatatable\":3}]";
$data = json_decode($json, true);
print_f($data[0]['label']);
Hope this helps!

How to access complex JSON data in PHP

Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;

Access JSON values in PHP

{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.

PHP: Accessing dictionaries from a JSON string

I'm writing a simple PHP script that makes an API call that returns JSON. However, I'm having trouble figuring out how to take that JSON string, convert it into a dictionary, and access nested dictionaries/data within it.
Here's what I have so far:
<?php
$id = $_REQUEST['id'];
$url = http://exampleURLThatReturnsJSONString.com
$rawData = file_get_contents($url);
I've read that you should use something like $decodedData = json_decode($rawData)
, but I'm not sure what to do next, especially if I want to access nested dictionaries with a key like Schedule.
Any help would be greatly appreciated, thanks!
json_decode($json, $assoc = false) converts the json string into an object by default, or into an array if you specify $assoc = true
If you have $assoc = false then you must access the values by $decoded_data->key. Whereas if you have $assoc = true then you can do $decoded_data['key']
You can just access the decoded data like this:
echo $decodedData['key'];
This wil echo the value of the item in the dictionary with key 'key'. Nested values can be accessed like this:
echo $decodedData['key1']['key2']['...'];
You can always use var_dump to show what's inside the result. Also, read the documentation on json_decode for more information.
json_decode return array or object to which access is like to array.
http://php.net/manual/en/function.json-decode.php

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

Categories