empty the old value of $array[] in php - 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.

Related

Put Mysql Query Result info multidimensional array

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

How to parse json array from mysql?

I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}

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

get json format using php in single loop array all other array set inner in the parent loop

i want this json format in php but i unable to do this.
{
"couresList_PVP": [
{
"pvp_ad_chptr_id": "9",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_name": "54654",
"offer_chapter_PVP": [
{
"pvp_ad_chptr_offr_id": "4",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
},
{
"pvp_ad_chptr_offr_id": "3",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
}]
},]
}
my PHP code is here. how I will do this? I'll get JSON response but different array not in a single with the array in array.
$sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_list` order by pvp_ad_chptr_id desc");
if(mysqli_num_rows($sql) > 0){
while($res=mysqli_fetch_assoc($sql)){
$url=$this->site_url.'images_console/chapter_banner_console/'.$res['pvp_ad_chptr_banner'];
$video=$this->site_url.'video_console/'.$res['pvp_ad_chptr_video_name'];
$images=array('pvp_ad_chptr_banner'=>$url,'pvp_ad_chptr_video_name'=>$video);
$data['couresList_PVP'][]=array_merge($res,$images);
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$data['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$data['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
}
//$data2=array_merge($data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data[]=array_push( $data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data=
// If success everything is good send header as "OK" and user details
$this->response($this->json($data), 200);
}
you can use combination of array and then encode it in json. please check below code.
$response = array();
$responseObj = array();
$courseList = array();
$courseArr = array();
while($res=mysqli_fetch_assoc($sql)){
$courseList['pvp_ad_chptr_id'] = $res['id'];
$courseList['pvp_ad_chptr_un_id'] = $res['pvp_ad_chptr_un_id'];
$courseList['pvp_ad_chptr_name'] = $res['pvp_ad_chptr_name'];
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$courseList['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$courseList[$i]['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
$courseArr[] = $courseList;
}
$response['couresList_PVP'] = $courseArr;
$responseObj = $response;
echo '<pre>';
echo json_encode($responseObj);
echo '</pre>';

Issue reading reading json tag in php

I am sending the following json to the server
{
"username":"abc#abc.com" ,
"password":"abc#123","access_key": "api_key",
"brands": [
{ "brandname": "Lee","xcoord": "1345",
"ycoord": "2345","color": {"colorId":8, "rvalue": "234",
"gvalue": "213","bvalue": "233" }
},
{ "brandname": "Pepe","xcoord": "432",
"ycoord": "4210","color": {"colorId":5, "rvalue": "234",
"gvalue": "213","bvalue": "233"}
}
],
"description": "free text",
"ocassion": 1, // an ocassion id goes here.
"other_tags": ["other1","other2"],
"upload_platform":"android|iOS|web"
}
When i try to read a specific object color, which resides brands array object as below I am unable to do so and the echo fails, printing nothing. I have never written php, its so easy in java to just use gson and define models that would fill every model up.
$userData = urldecode ( $_POST['form'] );
$json = json_decode ( $userData );
$brandTagsArr = $json->brands;
foreach ($brandTagsArr as $brandTag){
$brandName = $brandTag->brandName; // need to fetch the name and associate brand tag id
$xCoord = $brandTag->xcoord; //
$yCoord = $brandTag->ycoord;
$this->rest_image_upload_model->insertBrandTags($imageId, $brandName, $xCoord, $yCoord);
// insert colors
echo "insert brand tags <br>";
$color = $brandTag['color']; // returns nothing FAILS
$color = $brandTag->color; // returns nothing FAILS
echo "color id" . $color['colorId'];
$this->rest_image_upload_model->insertColorTag($imageId, $color['colorId'],$color['rValue'], $color['gValue'], $color['bValue']);
echo "insert color tags<br>";
// end inserting colors
}
the tag name for colors is rvalue,gvalue and bvalue, but you are using as rValue,gValue and bValue. I think thats the issue in your code.
$imageId = 1;
$a["username"] = "abc#abc.com";
$a["password"] = "abc#123";
$a["access_key"] = "api_key";
$a["description"] = "free text";
$a["ocassion"] = "1";
$a["brands"][0]["brandName"] = "Lee";
$a["brands"][0]["xcoord"] = "1345";
$a["brands"][0]["ycoord"] = "2345";
$a["brands"][0]["color"]["colorId"] = "8";
$a["brands"][0]["color"]["rvalue"] = "234";
$a["brands"][0]["color"]["gvalue"] = "213";
$a["brands"][0]["color"]["bvalue"] = "432";
$a["brands"][1]["brandName"] = "Lee";
$a["brands"][1]["xcoord"] = "1345";
$a["brands"][1]["ycoord"] = "2345";
$a["brands"][1]["color"]["colorId"] = "8";
$a["brands"][1]["color"]["rvalue"] = "234";
$a["brands"][1]["color"]["gvalue"] = "213";
$a["brands"][1]["color"]["bvalue"] = "432";
$json = json_decode(json_encode($a));
$brandTagsArr = $json->brands;
foreach ($brandTagsArr as $brandTag) {
// print_r($brandTag->color);exit;
$brandName = $brandTag->brandName; // need to fetch the name and associate brand tag id
$xCoord = $brandTag->xcoord; //
$yCoord = $brandTag->ycoord;
// $this->rest_image_upload_model->insertBrandTags($imageId, $brandName, $xCoord, $yCoord);
echo $imageId."===>".$brandName."===>".$xCoord."===>".$yCoord."<br>";
// insert colors
echo "insert brand tags <br>";
// $color = $brandTag['color']; // returns nothing FAILS
$color = $brandTag->color; // returns nothing FAILS
echo "color id =>" . $color->colorId;
echo $imageId."===>".$color->colorId."===>".$color->rvalue."===>".$color->gvalue."===>".$color->bvalue."<br>";
echo "insert color tags<br>";
// end inserting colors
}
For your convenience i ve created an array encoded and decoded there only.Hope it helps.

Categories