How to decode JSON to PHP array - php

I have a JSON output I would like to convert to a PHP array.
I tried with json_decode(), the problem is that there are arrays in the arrays.
They are the first weapons with PHP and I have never used JSON.
Can anyone help me?
Here is the JSON code:
{
"a": "text",
"b": "",
"c": [
{"name": "1", "id": "some text 1", "val": "x"},
{"name": "2", "id": "some text 2", "val": "x"},
{"name": "3", "id": "some text 3", "val": "x"}
]
}
I have to check that a variable is equal to name 1, contained in c, and if so, it also takes its id and val.
How can I do?
PS: I can compare two variables, but I do not know how to find name 1 and the corresponding data ..

$json = '{"a":"text","b":"","c":[{"name":"1","id":"some text 1","val":"x"},{"name":"2","id":"some text 2","val":"x"},{"name":"3","id":"some text 3","val":"x"}]}';
$json = json_decode($json,true);
echo $json["a"]."<br>";
echo $json["b"]."<br>";
echo $json["c"][1]["name"]."<br>";
echo "<pre>".print_r($json,true)."</pre>";

Related

Need MySQL query results as array of JSONs, NOT array of arrays holding JSONs

I'm running MySQL 8 in a dev environment, learning as I go. I'm running a very simple PHP 7 RestAPI.
Here is how I'm executing a simply MySQL lookup:
$blockStmt = 'SELECT JSON_ARRAY(JSON_OBJECT("value", titleId, "title", titleDesc))
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery);
print_r(json_encode($blockResult));
Here is how the result set is being returned by the print_r
[
[{"title": "Title 1", "value": "title1"}],
[{"title": "Title 2", "value": "title2"}],
[{"title": "Title 3", "value": "title3"}]
]
Here is how I WANT the results to be formatted:
[
{"title": "Title 1", "value": "title1"},
{"title": "Title 2", "value": "title2"},
{"title": "Title 3", "value": "title3"}
]
I've been working with the various JSON commands and can't seem to keep MySQL from encapsulating each result row as an array containing a single JSON, instead of just returning it as a JSON only.
Any tips? Thanks so much in advance!
Don't use the JSON functions, just return the columns that you want. mysqli_fetch_all() will then return associative arrays, and json_encode() will convert them to JSON.
$blockStmt = 'SELECT titleId AS value, titleDesc AS title
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery, MYSQLI_ASSOC);
print_r(json_encode($blockResult));

How to get values of json arrays in 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";

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);

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.

How to extract the JSON encoded POST parameters in PHP

I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Here my code works perfectly fine. However, I want to get all the parameters into a single object so that we can store them efficiently because otherwise there will be too many ifs and elses to get each parameter. So I have encoded the parameters as follows:
device = {
"id": "5",
"name": "abcd",
"imei": "1234"
}
But it is not working. Being new to JSON and PHP I do not know how to handle such cases. How can I achieve this?
use json_decode($_POST['device'], true) since your actually passing a parameter called 'device' to the php file.
You should pass json objects as follow:
{"device" : {
"id": "5",
"name": "abcd",
"imei": "1234"
}}
or if you have an array of devices
{"device" : [{
"id": "5",
"name": "abcd",
"imei": "1234"}
]}

Categories