Get JSON objects in PHP, not array - php

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}

$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}

I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.

You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num

First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Related

JSON Parsing Error: Warning: Attempt to read property on array

am trying to parse this JSON from a Football API using PHP.
Below is a subset of the JSON output.
Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.
$json = '{
"get": "predictions",
"parameters": {
"fixture": "198772"
},
"errors": [],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [{
"predictions": {
"winner": {
"id": 1189,
"name": "Deportivo Santani",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": "-3.5",
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
"percent": {
"home": "45%",
"draw": "45%",
"away": "10%"
}
}
}]
}';
I have tried the following codes but it does not work
$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;
The error i am getting is:
Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93
I also tried this but no luck.
echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;
appreciate any help or insights I can get.
thanks in advance.
Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.
$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;
"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like
$response->response.forEach(arrayItem => {
// arrayItem is the current element in the array you're looping though
})
You've probably missed that only value of "response" is an array, which has dictionary inside.
Try this: $response->response[0]->predictions->percent->home

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Unset all data except the data associated with a given value in url

I have a file that sends a request through curl, when I hit the url which is formatted as http://www.example.com/api/something?id=24 I get a series of arrays back in JSON form. It looks like:
24: {
pe: {
id: "24",
name: "Blah",
engine_src: "blah",
each_lender: "1",
soap_request: "0",
lenders: {
0: "3",
1: "1",
2: "6",
3: "12"
}
},
lenders: {
0: {
id: "1",
platform_id: "2",
lender_id: "3",
engine_id: "24",
status: "1",
engine_lender_id: "3",
engine_lender_name: "choice #1"
},
}
There are several other numbers and arrays in the list that look similar. I need to return the array that is associated with the id in the url and only that array.
I have set a new variable which looks like
$selected = (int)$_REQUEST['pe'];
How do I unset all other values except what is in my $selected variable?
Ok, then, assuming your response is in the variable $jsonresponse...
$selected = json_decode($jsonresponse,$assoc=TRUE);
$selected = $selected[$id];
Thank you for your help Charlene. This is how I ended up solving the problem. It is the same concept that Charlene posted just a slightly different format.
$selected = (int)$_REQUEST['pe'];
$save_me = $data[$selected];
unset($data);
$data = $save_me;
print_r($data);

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

Multidimensional Array Information Grabbing

I have an array that looks as such:
{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0,
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
and from number 1, I need to grab current_price. I have a foreach that grabs it from both, but I'm not sure how to only grab the info from number 1, being the second block of information - TSBC. Any ideas?
As you added the json tag to your question, I must note that you have presented an invalid json content. There is unexpected comma right after the number 0 within the first "stocks" object "available_shares": 0,.
So let's remove that comma and if we talk about "multidimensional array" let's decode our json string into associative array with json_decode function in such way:
// $str - is some part of your json string
$str = '{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
}}}';
$arr = json_decode($str, true);
// now we are able to get 'current_price' from the second element of array
var_dump($arr['stocks'][1]['current_price']);
// the output:
float 503.106

Categories