How to reformat JSON response using values from Array - php

Essentially I have the following script with the following response:
<?php
header('Content-Type: application/json');
$stmt = $pdo->prepare('
SELECT
`tablelist`.`id`,
`tablelist`.`content`
FROM `tablelist `
');
$stmt->execute([
]);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowcount = $stmt->rowCount();
if ($rowcount < 1) {
$response["error"] = TRUE;
echo json_encode($response);
}else{
echo json_encode($row);
}
?>
Current Response:
[
{
"id": 1,
"content": "Reason 1"
},
{
"id": 2,
"content": "Reason 2"
},
{
"id": 3,
"content": "Reason 3"
},
{
"id": 4,
"content": "Reason 4"
}
]
I would instead like to present this array as the following (no square brackets):
{
"error": false,
"content": {
"1": "Reason 1",
"2": "Reason 2",
"3": "Reason 3",
"4": "Reason 4"
}
I know I need to do the following:
$response["error"] = FALSE;
$response["content"][$row[id]] = $row[content];
But using this method I am not getting any values from the array.
How can present the values from the array the way?

Look at array_column function and Example #2 at https://www.php.net/manual/en/function.array-column.php
You can transform your rows like this but you must be aware of the uniqueness
$content = '[
{
"id": 1,
"content": "Reason 1"
},
{
"id": 2,
"content": "Reason 2"
},
{
"id": 3,
"content": "Reason 3"
},
{
"id": 4,
"content": "Reason 4"
}
]';
$from = json_decode($content, true);
$to = json_encode(array_column($from, 'content', 'id'), JSON_PRETTY_PRINT);
echo $to;
will result to
{
"1": "Reason 1",
"2": "Reason 2",
"3": "Reason 3",
"4": "Reason 4"
}
via https://3v4l.org/WL29a

You can do it very easily with PDO using the PDO::FETCH_KEY_PAIR fetch mode. It will use the first column from SQL as a key and the second as the value.
<?php
header('Content-Type: application/json');
$stmt = $pdo->prepare('
SELECT
`tablelist`.`id`,
`tablelist`.`content`
FROM `tablelist `
');
$stmt->execute();
$dataFromDB = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
if (!$dataFromDB) {
echo json_encode(['error' => true]);
} else {
echo json_encode(['error' => false, 'content' => $dataFromDB]);
}
This will produce an output similar to this if there were any rows returned from the SELECT:
{
"error": false,
"content": {
"1": "Reason 1",
"2": "Reason 2",
"3": "Reason 3",
"4": "Reason 4"
}
}

Related

Jotform: Parse returned data issue

I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}

Problem encoding PHP/MySQL arrays to JSON

I have the following tables in MySQL:
recipe: id_recipe (PKey), name_recipe, description
url_pic: id_img, url_img, id_recipe (FKey)
Using PHP, I am trying to get JSON which contains every recipe, along with its pictures' urls (an array). My problem is that the pictures array of recipe 2 includes the pictures of both recipes! I'm a beginner and I can't find where the problem is. I've included below the JSON I want, my PHP code, and the JSON I actually get:
Desired JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
PHP:
$sql = "SELECT id_recipe,name_recipe,description
FROM recipe";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['recipe'] = $row;
$sql2= "SELECT id_url,url
FROM url_img as u
WHERE u.id_recipe = '$row[id_recipe]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0){
while($row2 = $result2->fetch_array(MYSQL_ASSOC)) {
$array[] = $row2;
}
$data['pictures'] = $array;
}
$all[] = $data;
}
header('Content-Type: application/json');
echo json_encode($all,JSON_UNESCAPED_UNICODE);
}
Actual JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
},
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
Reset the array in each itteration
$result2 = $conn->query($sql2);
$array = []; // Add this line
if($result2->num_rows > 0){

PHP - parse xml to nested json

I am trying to parse a xml to a nested json structure with php.
This is my test script:
$json_drives = array();
foreach($drives->DR as $dr){
$current_drive = array();
$current_drive['id'] = $dr->ID;
$current_drive['name'] = $dr->NAME->D;
$json_drives[] = $current_drive;
}
echo("Finished");
// Parse and save
$f = json_encode($json_drives);
file_put_contents('test12345.json', $f);
I get a structure like that:
[
{
"id": {
"0": "1"
},
"name": {
"0": "Name 1"
}
},
{
"id": {
"0": "2"
},
"name": {
"0": "Name 2"
}
},
// ...
]
But I dont want the keys "id" and "name" to be nested. It should look like this:
[
{
"id": "1"
"name": "Name 1"
},
{
"id": "2"
"name": "Name 2"
},
// ...
]
How can I handle that?
Assuming your JSON's "drive" objects will always have this structure:
"id": {
"0": "Some ID"
},
"name": {
"0": "Some name"
}
You can use:
$current_drive['id'] = ((array) $dr->ID)[0];
$current_drive['name'] = ((array) $dr->NAME->D)[0];

How to Count Number of in in a field

I have a data base named nominator which has some fields
it have a in field named 'noinatedUnder' how can i show the number of inS to that field
this is the Raw text of
SELECT FROM Nominator
{
"result": [
{
"#type": "d",
"#rid": "#73:2",
"#version": 2,
"#class": "Nominator",
"isTemp": "true",
"id": "JJRXW",
"Email": "testuser#test.com",
"Name": "nijeesh",
"Phone": "7894561234",
"school": "#65:2",
"in_noinatedUnder": [
"#161:1",
"#162:1",
"#163:1",
"#164:0",
"#165:0",
"#166:0",
"#167:0",
"#168:0",
"#161:0",
"#162:0",
"#163:0"
],
"#fieldTypes": "school=x,in_noinatedUnder=g"
},
{
"#type": "d",
"#rid": "#74:0",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "SU7SV",
"Email": "npms#school.com",
"Name": "pon muthu",
"Phone": "7778455215",
"school": "#65:2",
"#fieldTypes": "school=x"
},
{
"#type": "d",
"#rid": "#75:1",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "4DZ86",
"Email": "sivaraj#testschool.com",
"Name": "sivaraj",
"Phone": "7788899445",
"school": "#65:2",
"#fieldTypes": "school=x"
},
{
"#type": "d",
"#rid": "#76:1",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "HFQJ1",
"Email": "klndk#knvd.com",
"Name": "dbhbsd",
"Phone": "8656548745",
"school": "#65:2",
"#fieldTypes": "school=x"
}
],
"notification": "Query executed in 6.12 sec. Returned 4 record(s)"
}
in this on the first entry there is 11 entrys in the in->nominated under area and 0 on everything else how to select this number using sql for each field
that is it should print
-----------
count | ----------
11
0
0
0
i did got the result using php
$query = "select * from `Nominator`";
$result = runquery($query);
$a = array();
for($i=0;$i<sizeof($result);$i++)
{
echo '<p>';
echo isset($result[$i]->oData->in_noinatedUnder)?sizeof($result[$i]->oData->in_noinatedUnder):0;
echo '</p>';
}
function runquery($query)
{
$client = new PhpOrient();
$client->hostname = 'localhost';
$client->port = 2424;
$client->username = 'root';
$client->password = 'hello';
$client->connect();
$client->dbOpen('tabe');
$result = $client->query($query);
$json = json_decode(json_encode($result));
if (sizeof($json) > 0) {
return $json;
} else {
return false;
}
}
So is there any way to get the count directly from sql it self, like select count(*) from nominator gives count of nominators
To get the number of vertexes in in try this query:
select in().size() from <class-name>
Hope it helps.
Regards

How create a response json with nested objects in php?

I want create a json response with nested json object and group my actual results by id_hotel
MY ACTUAL JSON RESPONSE
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}
]
}
MY PHP CODE for the encoding response
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["year"] = $row["year"];
$product["city"] = $row["city"];
$product["start"] = $row["start"];
$product["id_hotel"] = $row["id_hotel"];
$product["name"] = $row["name"];
$product["address"] = $row["address"];
$product["number_fr"] = $row["number_fr"];
$product["district"] = $row["district"];
$product["pr"] = $row["pr"];
$product["fres"] = $row["fres"];
$product["mode"] = $row["mode"];
$product["pos"] = $row["pos"];
$product["pes"] = $row["pes"];
$product["pis"] = $row["pis"];
$product["pus"] = $row["pus"];
// push single product into final response array
array_push($response["item"], $product);
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
What I desider
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": [{
"value" : "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{ "value" : "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}]
}
]
}
thanks in advance for your attention!!
Add option JSON_FORCE_OBJECT in function. You can read about it in http://tr2.php.net/manual/en/json.constants.php .
json_encode($response, JSON_FORCE_OBJECT) ;
1st, I suggest you a small change to save you some lines, and thus, i add some code to achieve what you want
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
$current_id = NULL;
while ($row = mysql_fetch_array($result)) {
if ( $row->id_hotel !== $current_id ){
$response["item"][] = $row;
$response["item"]["mode"] = array();
}
$current_item = end($response["item"]);
$current_item["mode"][] = array("value"=>$row->value, "pes"=>$row->pes);
$current_id = $row->id_hotel;
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
Let me know if it works.
Note: Only used 1 variable for mode, for testing purposes, and didn´t unset the variables that I put into mode array, but should be enough to see if the main idea works. Feeling a bit lazy :P

Categories