I am working on the application to get a response from the server in JSON format
I need the response in this format
{
"data" :[
{
"cat_id" : "1",
"post_id" : "2",
"sticker_info":[
],
"text_info" : [
{
"font_family" : "arial.otf",
"text" : "MY NAME",
"text_id" : "1",
"txt_color" : "#000000",
"txt_height" : "7.6",
"txt_order" : "1",
"txt_rotation" : "0",
"txt_width" : "96.5",
"txt_x_pos" : "70.2",
"txt_y_pos" : "4.7"
},
what i tried so for
$sql = "SELECT text_id,my_text,text_colour,x_position,y_position,width,height,rotation,text_order,font_family,cat_id,post_id FROM text_info where cat_id='$cat_id'";
$result = $conn->query($sql);
//store the entire response
$response = array();
//the array that will hold the titles and links
$posts = array();
while($row=$result->fetch_assoc()) //mysql_fetch_array($sql)
{
$text_id = $row['text_id'];
$my_text = $row['my_text'];
$text_colour = $row['text_colour'];
$x_position= $row['x_position'];
$y_position= $row['y_position'];
$width = $row['width'];
$height = $row['height'];
$rotation = $row['rotation'];
$text_order = $row['text_order'];
$font_family = $row['font_family'];
$cat_id = $row['cat_id'];
$post_id = $row['post_id'];
$text_info[]=array('text_id'=> $text_id, 'my_text'=> $my_text,'text_colour'=> $text_colour);
$output = array('text_information' => $text_info);
//each item from the rows go in their respective vars and into the posts array
$posts[] = array('text_id'=> $text_id, 'my_text'=> $my_text,'text_colour'=> $text_colour, 'x_position'=> $x_position,'y_position'=> $y_position, 'width'=> $width,'height'=> $height, 'rotation'=> $rotation,'text_order'=> $text_order, 'font_family'=> $font_family,'cat_id'=> $cat_id, 'post_id'=> $post_id
);
array_push($posts,$output);
}
//the posts array goes into the response
$data1=json_encode($posts);
$response['error'] = false;
$response['message'] = 'Data Retrived successfull';
$response['data'] = $data1;
and the output from the above code is
[
{
"text_id":"1"
,"my_text":"25"
,"text_colour":"#682e2e"
,"x_position":"42.5"
,"y_position":"17.5"
,"width":"57.7"
,"height":"29.4"
,"rotation":"0"
,"text_order":"3"
,"font_family":"arial.ttf"
,"cat_id":"1"
,"post_id":"1"
},
{"text_information":[
{"text_id":"1"
,"my_text":"25"
,"text_colour":"#682e2e"
}
]
},
how to get the required result I tried a lot but can't find the solution
I want the tex_information to be inside the array not in an object format that is
shown in top my actual requirement.
This will resolve your issue. add following array in your while loop.
$text_info[]= ['text_id'=> $text_id,
'my_text'=> $my_text,
'text_colour'=> $text_colour,
'x_position'=> $x_position,
'y_position'=> $y_position,
'width'=> $width,
'height'=> $height,
'rotation'=> $rotation,
'text_order'=> $text_order,
'font_family'=> $font_family];
//each item from the rows go in their respective vars and into the posts array
$posts['data'][] = [
'cat_id' =>$cat_id,
"post_id" => "2",
"sticker_info"=>[],
'text_info' => $text_info
];
print_R(json_encode($posts));
Output:
{"data":[{
"cat_id":"1",
"post_id":"2",
"sticker_info":[],
"text_info":[{
"text_id":1,
"my_text":"MY NAME",
"text_colour":"Yello",
"x_position":"70.2",
"y_position":"4.7",
"width":"96.5",
"height":"7.6",
"rotation":"0",
"text_order":"1",
"font_family":"arial.otf"
}]
}]
}
Try this code
$output = array();
while($row=$result->fetch_assoc()) //mysql_fetch_array($sql)
{
$posts=array();
$text_id = $row['text_id'];
$my_text = $row['my_text'];
$text_colour = $row['text_colour'];
$x_position= $row['x_position'];
$y_position= $row['y_position'];
$width = $row['width'];
$height = $row['height'];
$rotation = $row['rotation'];
$text_order = $row['text_order'];
$font_family = $row['font_family'];
$cat_id = $row['cat_id'];
$post_id = $row['post_id'];
$sticker_info[]=array('key'=>'value','key1'=>'value','key2'=>'value');
$text_info[]=array('text_id'=> $text_id,'font_family'=> $font_family,'text'=> $my_text,'txt_color'=> $text_colour,'txt_height'=> $height,'txt_order'=> $text_order,'txt_rotation'=> $rotation,'txt_width'=> $width,'txt_x_pos'=> $x_position,'txt_y_pos'=> $y_position);
$posts['data' = array('cat_id'=>$cat_id,'post_id'=>$post_id,'sticker_info'=>$sticker_info,'text_info'=>$text_info);
$output[] = $posts;
}
$output['error'] = false;
$output['message'] = 'Data Retrived successfull';
echo json_encode($output);
?>
Related
#UPDATED
I have this table :product_img_detail Table
i want to put the result to make this array of json:
{
"selectedColor": "black",
"black": {
"thumb": {
"image1": "../img/e-commerce/product/dark-small-1.jpg",
"image2": "../img/e-commerce/product/dark-small-2.jpg",
"image3": "../img/e-commerce/product/dark-small-3.jpg"
},
"large": {
"image1": "../img/e-commerce/product/dark-large-1.jpg",
"image2": "../img/e-commerce/product/dark-large-2.jpg",
"image3": "../img/e-commerce/product/dark-large-3.jpg"
}
},
"selectedSlide": 0
}
and this is what i've tried so far with help of #IT goldman:
$sImg = "SELECT prod_thumb160x90, prod_img1280x720 FROM product_img_detail WHERE prod_id=".$data2['id'];
$qPrd = mysql_query($sImg);
$rPrd = mysql_fetch_array($qPrd);
$imgPath = "img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
foreach ($rPrd as $row) {
$count++;
$arrSm["image$count"] = $imgPath.$rPrd['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath.$rPrd['prod_img1280x720'];
}
$arrImg = array("thumb"=>$arrSm, "large"=>$arrLg);
$res = array("selectedColor"=>"black", "black"=>$arrImg, "selectedSlide"=>0);
echo $json = json_encode($res);
the output of above code is:
{
"selectedColor": "black",
"black": {
"thumb": {
"image1": "img\/e-commerce\/product\/dark-small-1.jpg",
"image2": "img\/e-commerce\/product\/dark-small-1.jpg",
"image3": "img\/e-commerce\/product\/dark-small-1.jpg",
"image4": "img\/e-commerce\/product\/dark-small-1.jpg"
},
"large": {
"image1": "img\/e-commerce\/product\/dark-large-1.jpg",
"image2": "img\/e-commerce\/product\/dark-large-1.jpg",
"image3": "img\/e-commerce\/product\/dark-large-1.jpg",
"image4": "img\/e-commerce\/product\/dark-large-1.jpg"
}
},
"selectedSlide": 0
}
I'm curious, if i change the query to select * from the table, it looping until "image10", and if i change the query to select only 1 column from the table, it stop looping at "image2"!
Anyone can help me?
Please help i need to restructure with right & efficient code (and unescape the forwardslash), i've already stuck for 3 days...
After combining with #IT goldman code, i've found the answer:
$sImg = "SELECT * FROM product_img_detail WHERE prod_id=".$data2['id'];
$qPrd = mysql_query($sImg);
$imgPath = "img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
//foreach ($rPrd as $row) {
while($rPrd=mysql_fetch_array($qPrd)){
$count++;
$arrSm["image$count"] = $imgPath.$rPrd['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath.$rPrd['prod_img1280x720'];
}
$arrImg = array("thumb"=>$arrSm, "large"=>$arrLg);
$res = array("selectedColor"=>"black", "black"=>$arrImg, "selectedSlide"=>0);
echo $json = json_encode($res);
You need to loop the records (rows) and aggregate to the arrays with the proper keys (according to $count)
You need to loop the records (rows) and aggregate to the arrays with the proper keys (according to $count)
EDIT: I fixed usage of the now deprecated mysql_fetch_array
<?php
$sql = "SELECT * FROM product_img_detail WHERE prod_id = " . $data2['id'];
$qPrd = mysql_query($sql);
$imgPath = "../img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
while ($row = mysql_fetch_array($qPrd, MYSQL_ASSOC)) {
$count++;
$arrSm["image$count"] = $imgPath . $row['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath . $row['prod_img1280x720'];
}
mysql_free_result($qPrd);
$arrImg = array("thumb" => $arrSm, "large" => $arrLg);
$res = array("selectedColor" => "black", "black" => $arrImg, "selectedSlide" => 0);
echo $json = json_encode($res);
I am trying to insert data from database into an array, using while loop, here is my database:
id resulst
152556 0
152555 1
152553 1
152552 0
152551 1
152550 0
152549 1
Here is the code that I did:
$output = [
"online" => 0,
"success" => 0,
"servers" => []
];
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'] = [
$result['id'] => $result['result']
];
}
$output["online"] = 1;
$output["success"] = 1;
echo json_encode($output, JSON_PRETTY_PRINT );
Output:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0"
}
}
}
It only prints 1 element, not 5 as I would like. This is the output I want:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0",
152555: "1",
152553: "1",
152552: "0",
152551: "1"
}
}
}
Can you help me?
You overwrite the result on every loop of the loop. What you need to do is:
while($result = $mini_result->fetch()) {
$output['servers']['mini_result'][$result['id']] = $result['result'];
}
This does get quickly quite confusing. You can simplify it, like this:
$miniResult = [];
while($result = $mini_result->fetch()) {
$miniResult[$result['id']] = $result['result'];
}
$output['servers']['mini_result'] = $miniResult;
This what u need:
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
$output['servers']['mini_result'] = [];
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'][$result['id']] = $result['result'];
}
My database have three tables(category,catgory_details,questions), Now one category have many questions. I want to have a JSON response like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol",
"What is ur name?"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?",
"What is ur name?"
]
}
}
]
but my code is returning only one row from questions tables like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?"
]
}
}
]
Following is my php code:
<?php
header("Content-Type: application/json");
include('db.php');
$result = mysqli_query($conn,"SELECT * FROM categories ORDER BY id ASC");
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['category'] = $row['category'];
$id = $row['id'];
$detail_query = mysqli_query($conn,"SELECT * FROM category_details WHERE category_id=$id");
$question_query = mysqli_query($conn,"SELECT * FROM questions WHERE category_id=$id");
if($question_query->num_rows !== 0){
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
);
}
}
}
else{
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$myid = $detail_fetch['id'];
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
?>
What changes should I make in order to get my required JSON response?
Instead of building $row_array['deatils'] within the question_fetch loop, you should do it within the detail_fetch loop, and then populate just the questions sub-array within the question_fetch loop
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => array(),
);
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils']['questions'][] = $question_fetch['question'];
}
}
Try to change :
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
to :
'questions' => $question_fetch['question'],
So you will have the full array of questions included in the response.
i am trying to remove the old value of an array i searched over the internet i just found the method unset() using this solution but my case it seems different some how here is my full code
<?php
header('Content-type: application/json; charset=utf-8');
$link = mysqli_connect("localhost","root","");
mysqli_query($link,"SET NAMES UTF8");
$db= mysqli_select_db($link,"Mirsa") or die("Cannot select Database.");
if (isset($_GET['Product_ID']) ){
$productId;
$Menu_ID =$_GET['Product_ID'];
$query = "SELECT
mirsaProductId,mirsaProductCode,mirsaProductDescription,
mirsaProductPcsInCartoon,mirsaProductWeight,mirsaProductVolume,
mirsaProductCodeBType,mirsaProductCodeCType,FK_mirsaCategoryId
from mirsaProduct WHERE FK_mirsaCategoryId='$Menu_ID'";
$result = mysqli_query($link,$query) or die(mysql_error($link));
$response["Products"] = array();
$products = array();
while ($row = mysqli_fetch_array($result)) {
$image[]=array()
$products["mirsaProductId"] = $row["mirsaProductId"];
$products["mirsaProductCode"] = $row["mirsaProductCode"];
$products["mirsaProductDescription"] = $row["mirsaProductDescription"];
$products["mirsaProductPcsInCartoon"] = $row["mirsaProductPcsInCartoon"];
$products["mirsaProductWeight"] = $row["mirsaProductWeight"];
$products["mirsaProductVolume"] = $row["mirsaProductVolume"];
$products["mirsaProductCodeBType"] = $row["mirsaProductCodeBType"];
$products["mirsaProductCodeCType"] = $row["mirsaProductCodeCType"];
$productId = $row["mirsaProductId"];
$query2 = "SELECT mirsaProductUrlImage FROM mirsaProduct,mirsaProductImages
WHERE FK_mirsaProductId = '$productId' GROUP BY mirsaProductUrlImage";
$result2=mysqli_query($link, $query2);
while ($row2 = mysqli_fetch_array($result2))
{
$image [] = $row2["mirsaProductUrlImage"];
$products["mirsaProductUrlImage"]=$image;
}
array_push($response["Products"], $products);
}
die(json_encode($response));
}
// echoing JSON response
else {
// no products found
$response["success"] = 0;
$response["message"] = "No Products";
die(json_encode($response));
}
?>
i am getting a response of this way
{
ProductId: "1",
ProductCode: "118.023",
ProductDescription: "NEM OVAL (Transparent)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "0.104(m3)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
},
{
ProductId: "2",
ProductCode: "118.024",
ProductDescription: "NEM OVAL (Opac)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "7.55 - 8.05(KG)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
the second JSON object is not containing these 2 url of image it takes the old value of the $image[] so i need to reinitialised or empty his value in a way i need your help guys you are always our support
I am going to take a stab. Since you never really initialize $image to be an array. Do you actually intend for:
$image[] = array()
to be:
$image = array();
That would cause the $image array to be reset each time through the first while loop.
I have 2 table users(id,userid,fn,ln) and userdetails(id,userid,image,history,location,activity)
And i have written a query for first table to retrieve all the data and i want only history and location ,from second table.
i have retrieved the array and i am sending it to json_encode.
Now i want to retrieve the history,location and create a new key History and i want to add history location values to history key.
I need a query and json format for these.
For particular user i need to retrieve is own history
In both tables user id in common
Thanks in advance
$sth = mysql_query("SELECT * FROM users");$result = mysql_fetch_assoc($sth);
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['email'] = $data['email'];
$final_array[$i]['fname'] = $data['fname'];
$final_array[$i]['lname'] = $data['lname'];
$sth2 = mysql_query("SELECT id,places,act FROM user_dates WHERE user_id= '".$data['email']."'");
$result2 = mysql_fetch_assoc($sth2);
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("id" => $data2['id'],"places" => $data2['places'], "act " => $data2['act ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
[
{
"id": "81",
"user_id": "2011",
"fn": "asd.",
"ln": "wer",
"History": [
{
"id": "350",
"history": "make1",
"Location": "qwe"
}
]
},
{
"id": "82",
"user_id": "2012",
"fn": "asd1",
"ln": "wer1",
"History": [
{
"id": "350",
"history": "make2",
"Location": "qwe2"
}
]
}
]
Userdetails table contains multiple records per user. So you need to do sub query and get the results and then form a mulch-dimensional array. Finally, encode as a JSON.
$sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();
$result = $sth->fetchAll();
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['userid'] = $data['userid'];
$final_array[$i]['fn'] = $data['fn'];
$final_array[$i]['ln'] = $data['ln'];
$sth2 = $dbh->prepare("SELECT location,activity FROM userdetails WHERE userid= ".$data['id']."");
$sth2->execute();
$result2 = $sth2->fetchAll();
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("location" => $data2['location'], "activity " => $data2['activity ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);