Put Mysql Query Result info multidimensional array - php

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

Related

php with json nested array

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

empty the old value of $array[] in php

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.

Accessing nested object within array in PHP (Laravel)

I am struggling for quite a while on how to access nested object.
$dt = Carbon::parse($year.'-'.$month.'-1');
$godziny = array();
$gs = $lekarz->od;
$gz = $lekarz->do;
$ile = $gz-$gs;
for($j=0; $j<4*$ile; $j++){
if($j%4==0){
$wm = "00";
}
else{
$wm = ($j%4)*15;
}
if($gs+floor(($j/4)) < 10){
$dz="0".$dz = $gs+floor(($j/4));
} else{
$dz = $gs+floor(($j/4));
}
$godziny[$j]['godzina'] = $dz;
$godziny[$j]['minuty'] = $wm;
if(!empty(Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->get())){
$godziny[$j]['odbyta'] = Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->get();
dd(get_object_vars($godziny[$j]['odbyta']));
// $godziny[$j]['pacjent'] = Pacjent::where('id', '=', $godziny[$j]['odbyta']->{0}->pacjent_id);
} else {
$godziny[$j]['odbyta'] = '';
}
}
Everything works except for the last part. It seems like whatever way i try to access this data ( by using $godziny[$j]['odbyta']['pacjent_id'] or by $godziny[$j]['odbyta']->pacjent_id) it just won't work. I really don't know what to do.
That's my [$j]['odbyta] data:
{
"id": 1,
"pacjent_id": "13",
"lekarz_id": "1",
"data": "2017-04-05 10:15:00",
"odbyta": "0",
"created_at": "2017-04-05 16:14:42",
"updated_at": "2017-04-05 16:14:42"
}
That is code that generates data with a pattern:
$j's max number is 36
$godziny[0]['godzina'] = $dz //That's for setting hour to array
$godziny[0]['godzina'] = $wm; //That's for assigning minutes
$godziny[0]['odbyta'] <- that's of value of object that i listed above
How can i possibly access data from this object?
so $godziny[0]['odbyta'] can give me an value of object it contains?
Can't you just use Model->where...first()? and than access it as object:
$godziny[$j]['odbyta'] = Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->first();
$godziny[$j]['pacjent'] = Pacjent::where('id', '=', $godziny[$j]['odbyta']->pacjent_id);

PHP Array in wrong format

I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:
array[0] = project1, project2, project3;
array[1] = item1, item2, item3;
and I'm having this:
array[0] = project1;
array[1] = project2;
array[2] = project3;
and so on..
this is what I've done so far:
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$proj_name = $proj['proj_name'];
$proj_beg = $proj['proj_beg'];
$proj_end = $proj['proj_end'];
array_push($info, $proj_name, $proj_beg, $proj_end );
}
}
echo json_encode($info);
my query result gave me these result:
["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]
and this is my $.getJSON code:
$.getJSON("includes/get_area.php",function(data){
console.log(data);
})
What am I doing wrong?
Try this one; this will add a list in each one of the three array indexes.
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$info[0][] = $proj['proj_name'];
$info[1][] = $proj['proj_beg'];
$info[2][] = $proj['proj_end'];
}
}
echo json_encode($info);

php while loop error

I have a PHP MySQL fetch while loop as shown below in my script:
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
}
In that I have a problem. I get the result as like below (JSON):
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"},{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
But I need the result as like below:
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
As you can see configurablepone JSON is getting repeated for every loop so I am getting the value of the first product in second product also but I need to seperate like below:
First Product As Like Below
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}]
Second Product As Like Below
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}]
I have tried changing the loop but I haven't found any solutions. Kindly help me to solve this.
I think, your problem in line $subpro1[] = substr($subpro, 0, -1)."}";.
So, first call of this line save data from "Veg.Pizaa" into $subpro1[0].
Second call of this line save data from "Core i7 Pc" into $subpro1[1].
Then, line $subproa = "[".implode(",",$subpro1)."]"; merged all array elements.
Just Use unset($subpro1); after the array_push($totArr, $prodObj2);.
Below Is An example Source
Try This One This May Work
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
unset($subpro1);
}
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
$subpro1 = array();
}
try this in second while loop

Categories