Append JSON code to a JSON created from MySQL and PHP - php

I am trying to create dynamically a JSON from a MySQL, which seems fairly easy with this piece of code I found in this thread Create nested json object using php mysql.
However, I want to add before and after the $json_response some piece of JSON code.
The main code
$result = mysql_query("SELECT * FROM Places ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['title'] = $row['title'];
$row_array['image_url'] = $row['image_url'];
$row_array['subtitle'] = $row['subtitle'];
$row_array['buttons'] = array();
$id = $row['id'];
$option_qry = mysql_query("SELECT * FROM Places where id=$id");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['buttons'][] = array(
'type' => $opt_fet['type'],
'caption' => $opt_fet['caption'],
'url' => $opt_fet['url'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response, JSON_PRETTY_PRINT);
Produces this JSON
[
{
"title": "Name of the place",
"image_url": "image.jpg",
"subtitle":Additional info",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link "
}
]
},
{
"title": "Name of the place 2",
"image_url": "image2.jpg",
"subtitle":Additional info2",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link 2"
}
]
}
]
I have somehow to add the following code before the already created JSON
{
"version": "v2",
"content": {
"messages": [
{
"type": "cards",
"elements":
And this code in the end
}
]
}
}

Pretty simple:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
Personally, I'd rename $json_response to $messages for clarity purposes.

While declaring array $json_response = array(); you can actually prepare it with your default values require like
$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
echo json_encode($stdObj, JSON_PRETTY_PRINT);

Related

How to modify json key

I need some help to reorder the data in a json file.
I have these few lines :
foreach($rows as $row) {
$data[] = array(
"$row[0]" => array(
"name" => "$row[1]",
"value" => "$row[2]",
"conso" => "$row[3]",
"ml" => "$row[4]"
)
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);
This function allows me to obtain something like this :
This function allows me to obtain something like this :
{
"0": {
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
}
},
"1": {
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
}
I would like something like that :
{
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
},
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
Get rid of a layer of array, and specify the key you want. You also don't need to quote all the variables like that.
foreach($rows as $row) {
$data[$row[0]] = array(
"name" => $row[1],
"value" => $row[2],
"conso" => $row[3],
"ml" => $row[4]
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);

Nested array in json data in php

I need to show Mysql data in json nested array like
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
},
{
"id": "2",
"title": "Title 2",
},
{
"id": "3",
"title": "Title 3",
}
]
}
Code I am trying is
$sql = "SELECT * FROM `categories`";
$res_data = mysqli_query($conn,$sql);
$rows = array();
while($row = mysqli_fetch_array($res_data)){
$rows[] = $row;
foreach($rows as $row){
$rows = ['id' => $row['id'], 'title' => $row['title']];
}
}
$data = array('status' => true, 'categories' => array($rows));
echo json_encode($data);
But what I get is only with one record in the nested array i.e
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
}
]
}
How can I achieve my requirement?
If you want to avoid duplication, leave out the foreach loop and just write in the while loop:
$rows[] = ['id' => $ row ['id'], 'title' => $ row ['title']];
…because with the while loop, you already run through the row array.
You don't need any loops. Mysqli already returns a nested array which you can directly output to JSON
$res_data = $conn->query("SELECT id, title FROM `categories`")
echo json_encode(['status' => true, 'categories' => $res_data->fetch_all(MYSQLI_ASSOC)]);

PHP JSON encode doesn't return array keys [duplicate]

This question already has answers here:
PHP Array to Json Object
(6 answers)
I would like json_encode in PHP to return a JSON array even if the indices are not in order
(5 answers)
json_encode PHP array as JSON array not JSON object
(4 answers)
Closed 3 years ago.
I am having trouble with ids in an associative array not being encoded in the JSON string. I have the following PHP snippet:
require_once("../common/connection.php");
$hermesDB_PRST = $HERMESPDO->prepare("SELECT * FROM tblTX INNER JOIN tblUsers ON tblTX.SourceUserID = tblUsers.UserID WHERE TargetUserID = :TargetUserID AND TargetNotified = 0");
$hermesDB_PRST->bindValue(":TargetUserID", "2");
$hermesDB_PRST->execute() or die($HERMESPDO->errorInfo());
$NotificationsStack = array();
while ($hermesDB_RSLT = $hermesDB_PRST->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
$ID = $hermesDB_RSLT["ID"];
$Source = $hermesDB_RSLT["Source"];
$Msg = $hermesDB_RSLT["Msg"];
$Notification = array(
"TXID" => $ID,
"Source" => $Source,
"Msg" => $Msg
);
$NotificationsStack[$ID] = $Notification;
}
$sRetData = array(
"Balance" => 0,
"Transactions" => $NotificationsStack
);
echo json_encode($sRetData, JSON_PRETTY_PRINT);
Which correctly produces the following json result:
{
"Balance": 0,
"Transactions": {
"1": {
"TXID": "1",
"Source": "456",
"Msg": "reason 1"
},
"3": {
"TXID": "3",
"Source": "456",
"Msg": "reason 2"
}
}
}
But if I do it manually like this:
$NotificationsStack = array();
$ID = "0";
$Notification = array(
"ID" => $ID,
"Source" => "123",
"Msg" => "haha"
);
$NotificationsStack[$ID] = $Notification;
$ID = "1";
$Notification = array(
"ID" => $ID,
"Source" => "456",
"Msg" => "hehe"
);
$NotificationsStack[$ID] = $Notification;
$sRetData = array(
"Balance" => 0,
"Transactions" => $NotificationsStack
);
echo json_encode($sRetData, JSON_PRETTY_PRINT);
I get:
{
"Balance": 0,
"Transactions": [
{
"ID": "0",
"Source": "123",
"Msg": "haha"
},
{
"ID": "1",
"Source": "456",
"Msg": "hehe"
}
]
}
So I'm wondering why in the second case the IDs are not "displayed" as it would in an associative array. Instead just a list appears. This despite the fact that I enter the IDs as strings and not as integers.
Any help would be appreciated.

json_encode with correct format

I can't get my json_encode format that I need.
Current Format:
{
"substantiv": [
{"text":"auto"},
{"text":"noch ein auto"}
],
"verben":[
{"text":"auto fahren"}
]
}
What I need:
[
{
"type":"substantiv",
"items": [
{"text":"auto"},
{"text":"noch ein auto"}
]
} , {
"type":"verben",
"items": [
{"text":"auto fahren"}
]
}
]
My current php code:
$data = array();
while($row = $rs->fetch_assoc()){
$tmp = array(
"text" => $row['gtext']
);
$data[$row['type']][] = $tmp;
}
echo json_encode($data);
I have tried a few things but just can't figure it out.
You could try something like this
while($row = $rs->fetch_assoc()){
$data[$row['type']][] = array(
"text" => $row['gtext']
);
}
$result = array();
foreach($data AS $type => $items) {
$result[] = array(
'type' => $type,
'items' => $items
);
}
echo json_encode($result);
What you actually want is this:
[
{
"type": "substantiv",
"items": [
{
"text": "auto"
},
{
"text": "noch ein auto"
}
]
},
{
"type": "verben",
"items": [
{
"text": "auto fahren"
}
]
}
]
which is the output you'll get from Louis H.'s answer's code.

mixare json, how to configure?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
From this code, it will generate like this,
[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]
But I want something like this,
{ "status": "OK", "num_results": 3, "results":
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" },
{ "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" },
{ "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" }
] }
How can I do it?
Fetch all your results or do it row by row. Choose yourself. En create the json array afterwards. You also might want to look at your use of mysql_* functions. As they are deprecated now. And you should really switch to MySQli/PDO
$result = array();
while($row = mysql_fetch_assoc($q)) {
$result[] = $row;
}
$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
To add the structure you wish to have in your json, first you must create that structure from php before encoding it to json.
$objects = array();
while ($r = mysql_fetch_associ($rs) {
$a = new stdClass();
$a->status = $r['status'];
...
$a->results = array('id' => $r['id']....)
$objects[] = $a;
}
echo json_encode($objects);
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
$output = array();
if($q) {
$output['status'] = 'OK';
}
$output['num_results'] = mysql_num_rows($q);
while($e=mysql_fetch_assoc($q)) {
$output['results'][]= array (
'id' => $e['id'],
'lat' => $e['latitude'],
'lng' => $e['longitude'],
'elevation' => $e['elevation'],
'title' => $e['title'],
'distance' => $e['distance'],
'has_detail_page' => $e['has_detail_webpage'],
'webpage' => $e['webpage'],
);
}
print(json_encode($output));

Categories