How to get values of json arrays in php - php

I have a json array within {} braces and which are retrieved from $response5.
$json ='[
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "VASAN/000000037",
"Row_ID": 332713,
"Milkman_Code": "310",
"Farmer_Name": "VASANTHA",
"Gender": "Female",
"Received_Quantity": 1.3
},
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "CHIND/000000366",
"Row_ID": 332714,
"Milkman_Code": "449",
"Farmer_Name": "CHINDIRA E",
"Gender": "Female",
"Received_Quantity": 3
},
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "PERUN/000000017",
"Row_ID": 332715,
"Milkman_Code": "492",
"Farmer_Name": "V.Perundevi",
"Gender": "Female",
"Received_Quantity": 3
}
]';
$data=json_decode($json,true);
$your_string="";
foreach($data as $key=>$v){
$your_string.=$data[$key]['Collectioncentre_Name'].",".$data[$key]
['Session_ID'].",".$data[$key]['Date'].",".$data[$key]
['MilkSession'].",".$data[$key]['Farmer_ID'].",".$data[$key]
['Row_ID'].",".$data[$key]['Milkman_Code'].",".$data[$key]
['Farmer_Name'].",".$data[$key]['Gender'].",".$data[$key]
['Received_Quantity']."\r\n";
}
$csvdata= trim($your_string, ",");
//$csvdata = $your_string;
echo $csvdata."\r\n";
Actually these json arrays are the output from $response5. And if I put the code like $json ='[$response5;] instead of adding whole arrays, am not getting the actual result which I got when I added array values. Did I miss anything or did I need to add more code?

To put the various comments together, when trying to put the whole JSON together from the original data, instead of...
$json ='[$response5;]
to make it a valid JSON array you need to use...
$json ="[$response5]";
Then to output each row of data plus headings (using implode rather than long winded adding each field together), you can use...
$data=json_decode($json,true);
$your_string=implode(",",array_keys($data[0])).PHP_EOL;
foreach($data as $key=>$v){
$your_string.=implode(",",$v).PHP_EOL;
}
echo $your_string."\r\n";

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

Filter response from json with php

for example, i have json result like this
[
{
"title": "x1",
"url": "domain.com"
},
{
"title": "x2",
"url": "example.com/"
},
{
"title": "x3",
"url": "site.com/cam"
},
]
The result of json will be randomly, i want to scrape ['x']['url'] path from that json, but the value of ['url'] must be "site.com/cam", and as you know, the results from json will change randomly, so I do not know which json path with value is "site.com/cam".
is there any suggestion? Thank you
Try this
$index = array_search('site.com/cam',array_column(json_decode($json),'url'));
Sandbox
https://3v4l.org/72tsZ
Output
$index = 2
Oh and there is a typo in your JSON
}, <-- remove comma here.
]

How to fetch PHP database values in Json?

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.
My code is following:
<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
"name": "A", // Here database values come $row['name'];
"children": [
{
"name": "B",
"children": [
{"name": "B-1"}
]
},
{
"name": "C",
"children": [
{"name": "C-1", "size": 1082},
{"name": "C-2", "size": 1681}
]
},
{
"name": "D",
"children": [
{
"name": "D-1",
"children": [
{"name": "D-1 1", "size": 1302},
{"name": "D-1 2", "size": 6703}
]
},
{"name": "D-2", "size": 16540}
]
}
]
}
<?php
}
?>
In this example Im using the mysqli driver. Do not use the mysql driver.
you just need to convert your output data into a json object.
Its possible to extract all the rows at once which is going to give you a marginally less overhead.
$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.
if you need specific keys, then manipulate your query to rename columns as necessary eg.
$query = "select name as firstname from ....";
You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).
You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

Get JSON objects in PHP, not array

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...

Save JSON objects' pairs in an array

I am very new to JSON and i really need help. So I have been given this $oldAuctions object and after using PHP's json_decode function (json_decode($oldAuctions, TRUE);) it returned me something like this that has 11 objects with 9 set of name/value pairs in each...
{
"recent_results": [
{
"closing_yield": "0.800",
"auction_id": "106",
"use_buy_it": "0",
"issuer": "National Bank",
"term": "1 Year",
"is_charity": "1",
"end_date": "12-26-2012",
"closing_price": "100.000000",
"issue_type": "FDICs"
},
{
"closing_yield": "1.090",
"auction_id": "339",
"use_buy_it": "0",
"issuer": "National Bank",
"term": "1 Year",
"is_charity": "1",
"end_date": "12-12-2012",
"closing_price": "100.000000",
"issue_type": "FDICs"
},
{
"closing_yield": "2.000",
"auction_id": "041",
"use_buy_it": "0",
"issuer": "National Bank",
"term": "5 Year",
"is_charity": "1",
"end_date": "09-11-2012",
"closing_price": "100.000000",
"issue_type": "FDICs"
}
]
}
Now I need to grab each pair and save their values in an array. For example, I want to grab the auction_id and save it's values in an array.....how can I do that?
Also, just for simple testing purpose I tried to print out the values first...but that didn't work either...
foreach($oldAuctions as $IDs)
{
echo 'Ids: '.$IDs->auction_id;
}
I would really appreciate your help. Thank you!
After invoking json_encode your array $oldAuctions has become a JSON string. You can not iterate through it as array or object as its a string.
As $oldAuctions is already an array you can simply use forach
foreach($oldAuctions['recent_results'] as $result){
echo 'Ids: '.$result['auction_id']. "\n";
}

Categories