PHP JSON array from query - php

I'm not a php developer, but trying to get an array within an array from this query:
SELECT distinct d.DiscussionId as DiscussionId, d.AvatarId as AvatarId, d.Heading as Heading, d.body as Body, c.commentid as CommentId, c.userid as UserId, c.comment as Comment
FROM Discussion AS d
INNER JOIN Comments AS c ON d.discussionid = c.discussionid
WHERE d.DiscussionId = c.DiscussionId
The JSON output is:
[
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "1",
"UserId": "2",
"Comment": "This is a comment i made"
}
]
},
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "2",
"UserId": "2",
"Comment": "This is a second comment"
}
]
}
]
What I need is to nest all Comments in one Discussion.
the php code is below, no error but not giving the output i want, for each discussion there maybe several comments so i need DiscussionId:1 displayed only once with multilple comments array
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$record++;
$model[] = array();
$model[$record]['DiscussionId'] = $e['DiscussionId'];
$model[$record]['AvatarId'] = $e['AvatarId'];
$model[$record]['Heading'] = $e['Heading'];
$model[$record]['Body'] = $e['Body'];
$model[$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);

You are selecting many comments from a single dicussion.
You should overwrite that variable instead of creating a new element at each iteration:
$model = array();
while($e = mysql_fetch_assoc($result)){
//We overwrite the same variable, that's ok
$model['DiscussionId'] = $e['DiscussionId'];
$model['AvatarId'] = $e['AvatarId'];
$model['Heading'] = $e['Heading'];
$model['Body'] = $e['Body'];
//Only comments would be an array
$model['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}

try it like this:
Added Disscussion Id as an index for the array, should work for you. Just off the top of my head, not tested.
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
$model = array();
while($e = mysql_fetch_assoc($result)){
$record++;
$model[$e['DiscussionId']][$record]['AvatarId'] = $e['AvatarId'];
$model[$e['DiscussionId']][$record]['Heading'] = $e['Heading'];
$model[$e['DiscussionId']][$record]['Body'] = $e['Body'];
$model[$e['DiscussionId']][$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);

Try this:
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = 0;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$model[] = array();
$model[$record][$e['DiscussionId']]['AvatarId'] = $e['AvatarId'];
$model[$record][$e['DiscussionId']]['Heading'] = $e['Heading'];
$model[$record][$e['DiscussionId']]['Body'] = $e['Body'];
$model[$record][$e['DiscussionId']]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
); ;
$record++;
}
print json_encode ($model);
This might help you. Dont forget to accept answer if it helps.

It's not possible with just changing the SQL query: you need to change the server-side code (PHP, as I understand) which transorms query results to JSON.

Related

How to make multiple records in array php

From my database i am receaving array, that i`m later sending using Fetch Api to my frontend and display data that was send. It looks like this:
return $stmt->fetchAll(PDO::FETCH_NAMED);
and the given output in JSON is like this:
[
{
"name": [
" name1",
" name2",
" name3"
],
"date": "2022-02-05 12:00:00",
"round": "3",
"coordinate x": "number",
"coordinate y": "number",
"leauge_id": 4
}, etc.
What i want to do is to replace fields coordinate x, coordinate y and insert into this array new field location(based on GoogleGeocodeAPI i will transofrm coordinates into location name) and insert it into this array so i will later be able to display this location.
Here is what i tried to do:
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result['nameA'] = $match['name'][0];
$result['nameB'] = $match['name'][1];
$result['nameC'] = $match['name'][2];
$result['date'] = $match['date'];
$result['round'] = $match['round'];
$result['leauge_id'] = $match['leauge_id'];
$result['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
}
return $result;
Output from JSON:
{
"nameA": " name",
"nameB": " name",
"nameC": " name",
"date": "2022-02-05 12:00:00",
"round": "29",
"leauge_id": 6,
"location": "location"
}
But it ends up that i`m kinda overwriting the posistion and in the end i am sending only one, the last record. How can i make this work?
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result[] = [
'nameA' => $match['name'][0],
'nameB' => $match['name'][1],
'nameC' => $match['name'][2],
'date' => $match['date'],
'round' => $match['round'],
'leauge_id' => $match['leauge_id'],
'location' => $this->reverse_geocode($match['coordinate x'],$match['coordinate y']),
];
}
return $result;
One way to do this is to create a variable $i and use that to key your array...
<?php
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
$i=0;
foreach ($matches as $match){
$result[$i]['nameA'] = $match['name'][0];
$result[$i]['nameB'] = $match['name'][1];
$result[$i]['nameC'] = $match['name'][2];
$result[$i]['date'] = $match['date'];
$result[$i]['round'] = $match['round'];
$result[$i]['leauge_id'] = $match['leauge_id'];
$result[$i]['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
$i++;
}
return $result;

Insert multidimensional array into multidimensional json in PHP

I want to insert some data into sub in json data with my data in database
here is my code:
$sql = "SELECT * FROM pharma_data";
$result = mysqli_query($conn, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
$row_array['batch'] = $row['batch_no'];
$row_array['category'] = $row['category'];
$row_array['measurement'] = $row['measurement'];
$row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
$row_array['date'] = $row['date_added'];
$row_array['expiration'] = $row['expiration_date'];
$row_array['type'] = $row['medicin_type'];
$row_array['supplier'] = $row['supplier'];
array_push($data,$row_array);
}
$convert = json_encode($data);
echo $convert;
but the output of my code is:
[{"id":"8","name":"Test Product Name Pharmacy","batch":"Test Product Name Pharmacy","category":"Test Category Pharmacy","measurement":"1mg","stock":"2","price":"15","date":"February 18, 2021, 11:36 am","expiration":"2021-02-18","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"9","name":"Alaxan","batch":"Test user medicine Supplies","category":"Test Category Pharmacy","measurement":"1mg","stock":"66","price":"63.43","date":"February 28, 2021, 4:45 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"10","name":"Medicol","batch":"987","category":"Test Category Pharmacy","measurement":"1mg","stock":"15","price":"123.23","date":"February 28, 2021, 5:42 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"11","name":"test","batch":"test","category":"Test Category Pharmacy","measurement":"213","stock":"32","price":"123.78","date":"February 28, 2021, 6:43 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"}]
Want output like this:
{
"total": 800,
"totalNotFiltered": 800,
"rows": [
{
"id": 0,
"name": "Item 0",
"price": "$0"
},
{
"id": 1,
"name": "Item 1",
"price": "$1"
}
]
}
enter image description here
You need to filter out $data before sending it to the response so it means we need a function myFilter to filter the $data elements and we can filter all the elements in the array using array_map(). The total and totalFiltered column seems to give the total number of rows in $data hence the count(). Try the code below:
function myFilter($a) {
$row['id'] = $a['id'];
$row['name'] = $a['name'];
$row['price'] = $a['price'];
return $row;
};
$filterData = array(
'total' => count($data),
'totalNotFiltered' => count($data),
'rows' => array_map("myFilter", $data)
);
$convert = json_encode($filterData);
echo $convert;
Demo code would be here: https://ideone.com/pZCUbG
You need to convert the returned data. Something like:
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
// $row_array['batch'] = $row['batch_no'];
// $row_array['category'] = $row['category'];
// $row_array['measurement'] = $row['measurement'];
// $row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
// $row_array['date'] = $row['date_added'];
// $row_array['expiration'] = $row['expiration_date'];
// $row_array['type'] = $row['medicin_type'];
// $row_array['supplier'] = $row['supplier'];
$data[] = $row_array; // Same as array_push($data,$row_array);
}
$final_data = array(
'total' => count($data),
'totalNotFiltered' => '',
'rows' => $data
);
$convert = json_encode($final_data);
echo $convert;
Commented out the data that isn't needed in this context (maybe you need it to use elsewhere, not sure. If so just uncomment back)
Not sure with totalNotFiltered as I don't know how you are calculating this. Maybe you can work with that and this gives you an idea to work with.

fetching multiple rows and display in json

I have a PHP code like:
while ($row2 = mysqli_fetch_assoc($check2)) {
// $leadarray[] = $row2;
$service_id[$i] = $row2['service_id'];
$row1['service_id'][$i] = $service_id[$i];
$service_name[$i] = $row2['service_name'];
$row1['service_name'][$i] = $service_name[$i];
$i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);
getting output like
{
"leaddetails": [
{
"service_id": [
"7",
"2"
],
"service_name": [
"Past Control Services",
"Civil Finishing"
],
}
]
}
I want output like:
"service_id": [
1: "7",
2: "2"
],
"service_name": [
1: "Past Control Services",
2: "Civil Finishing"
],
or
[
"service_id": "7",
"service_name": "Past Control Services",
"service_id": "2",
"service_name": "Civil Finishing",
]
$trimmed1 is considered an object when passing it to json_encode (associative array in PHP) because you explicitly give it a key (considered an object property in JSON):
$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';
This will result in json_encode encoding $trimmed1 into an object:
{
"leaddetails": "foobar"
}
To get your desired result, have $trimmed1 be considered an ARRAY when passed to json_encode.
$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
second option is not posible
you can make like this
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
using class for make like that
class Data{
$service_id;
$service_name;
}
$obj = new Array();
while ($row2 = mysqli_fetch_assoc($check2)){
$data = new Data();
$data->service_id = $row2['service_id'];
$data->service_name = $row2['service_name'];
array_push($obj, $data);
}
echo json_encode($obj);
Create the 2-dimensional array first. Then push onto the nested arrays during the loop.
$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
$result["service_id"][] = $row["service_id"];
$result["service_name"][] = $row["service_name"];
}
echo json_encode($result);

Php Mysql Nested Category Subcategories Json Response

I would like to display categories and subcategories as json response using php mysql. I have three level categories. I am running this query but results not coming as expected. please help me to solve this.
I need json response like below
[{
"id": "1",
"name": "Electronics",
"categorieslevelone": [{
"id": "2",
"name": "Mobiles",
"categoriesleveltwo": [{
"id": "3",
"name": "Samsung",
"parent_id": "2"
}, {
"id": "4",
"name": "Nokia",
"parent_id": "2"
}]
}]
My Code:
header('Content-Type: application/json');
$sql = "select * from category where category_id = 0";
$q = $this->db->conn_id->prepare($sql);
$q->execute();
$json_response = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$row_array = array();
$row_array['id'] = $row['id'];
$row_array['name'] = $row['name'];
$row_array['categorieslevelone'] = array();
$id = $row['id'];
$sqltwo = "select * from category where category_id = ? ";
$r = $this->db->conn_id->prepare($sqltwo);
$r->bindParam(1, $id);
$r->execute();
while ($data = $r->fetch(PDO::FETCH_ASSOC)) {
$id2 = $data['id'];
$row_array['categoriesleveltwo'] = array();
$row_array['categorieslevelone'][] = array(
'id' => $data['id'],
'name' => $data['name'],
);
$sql3 = "select * from category where category_id = ? ";
$s = $this->db->conn_id->prepare($sql3);
$s->bindParam(1, $id2);
$s->execute();
while ($list = $s->fetch(PDO::FETCH_ASSOC)) {
$row_array['categoriesleveltwo'][] = array(
'id' => $list['id'],
'name' => $list['name'],
);
}
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
I'm getting a result like you mentioned above. Chenck this out. You have to convert procedural into Object oriented method.
$main_cat = array();
while($row = mysqli_fetch_assoc($query))
{
$query2 = mysqli_query($con,'Select category_id as id,category_name as name from category where parent_id = '.$row['id'].'');
$sub_cat = array();
while($row1 = mysqli_fetch_assoc($query2))
{
$query3 = mysqli_query($con,'Select category_id as id,category_name as name from category where parent_id = '.$row1['id'].'');
$sub_cat2 = array();
while($row2 = mysqli_fetch_assoc($query3))
{
array_push($sub_cat2, $row2);
}
$row1['categoriesleveltwo'] = $sub_cat2;
array_push($sub_cat, $row1);
}
$row['categorieslevelone'] = $sub_cat;
array_push($main_cat, $row);
}
echo json_encode($main_cat);
?>
Hope its will satisfy your requirement
I know this answer is already accepted, but I thought it would make nice code kata.
Code below will build tree structure from adjacency list that you have in db. There are more ways to maintain tree structures, but there's no easy way - all methods involve maintance/code efficiency trade offs.
I used references to build whole tree in one loop regardless of nested nodes number and order in which rows are fetched (would be much easier when parent node was already fetched, but would need extra attention to changes in db) - this way you could order categories alfabetically with db query.
Since it works for any nesting level all children are stored under subcategories key (opposed to categorieslevelxxx), but each subtree might be processed the same way.
...
$link = [];
$data = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$parent = $row['category_id'];
unset($row['category_id']);
empty($link[$id]) or $row += $link[$id];
isset($link[$parent]['subcategories']) or $link[$parent]['subcategories'] = [];
$link[$parent]['subcategories'][] = $row;
$last_idx = count($link[$parent]['subcategories']) - 1;
$link[$id] = & $link[$parent]['subcategories'][$last_idx];
}
$data = $link[1];
unset($link); //tree might be cached here.
$link[1] at the end means we want category 1 and all it's descendants, but you might take any other node. $link[0] would take entire tree when there's more root categories (category_id = 0 in db points to "virtual" root).

Writing to JSON with PHP

I need help with my json output. At present my output is as so:
[
[
{
"ING_SW_CB": "5",
"SB_SW_CB": "3",
"NG3_SW_CB": "1",
"Mould_Close": "4",
"Leak_Test": "5",
"ML_Load": "6",
"Pre_Heat": "3",
"Dispense": "9",
"A310": "7",
............
}
]
]
I’d like it to be as following with "key" & "value" included in the output.
{"key":"ING_SW_CB", "value": "5"},
{"key":"SB_SW_CB", "value": "3"},
..............................
Hers is my PHP script:
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
$row_array['ING_SW_CB'] = $row['ING_SW_CB'];
$row_array['SB_SW_CB'] = $row['SB_SW_CB'];
$row_array['NG3_SW_CB'] = $row['NG3_SW_CB'];
$row_array['Mould_Close'] = $row['Mould_Close'];
$row_array['Leak_Test'] = $row['Leak_Test'];
$row_array['ML_Load'] = $row['ML_Load'];
$row_array['Pre_Heat'] = $row['Pre_Heat'];
$row_array['Dispense'] = $row['Dispense'];
$row_array['A310'] = $row['A310'];
$row_array['Gelation'] = $row['Gelation'];
$row_array['Platen'] = $row['Platen'];
$row_array['Mainline_Unload'] = $row['Mainline_Unload'];
$row_array['De_mould'] = $row['De_mould'];
$row_array['Clean_Up'] = $row['Clean_Up'];
$row_array['Soda_Blast'] = $row['Soda_Blast'];
$row_array['Miscellaneous'] = $row['Miscellaneous'];
//push the values in the array
array_push($json_response,$row_array);
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);
I need the keywords "key" & "value" added to the output so I can popuate a D3 chart.
You need to loop on the row's results and build more arrays:
while(...) {
$temp = array();
foreach($row as $key => $value) {
$temp[] = array('key' => $key, 'value' => $value);
}
$json_response[] = $temp;
}
Loop over the columns:
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$json_row = array();
foreach ($row as $key => $value) {
$json_row[] = array('key' => $key, 'value' => $value);
}
$json_response[] = $json_row;
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
//push the values in the array
foreach($row as $k=>$v){
$my_array = array("key"=>$k, "value"=>$v);
}
array_push($json_response,$my_array);
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);

Categories