Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.
Related
i have many to many relationship
like this :
Server version: 10.4.17-MariaDB
table colors(id,name).
table items(id,title....).
table item_color(id,items_id,color_id).
my query is like this :
SELECT items.*,colors.name FROM items,item_color,colors
where
items.id = item_color.item_id
and
colors.id = item_color.color_id
i use php function json_encode().
how to return this :
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
0 : "pink",
1 : "white"
]
}
instead if this:
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "pink"
},
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "red"
},
There's 2 way to do it:
If you want to keep your query, you must parse the data first before you parse it to json.
...
function regroup_color($data = array()){
$ret = array();
foreach($data as $d){
$id = $d['id'];
if(!isset($ret[$id])){
$color = $d['color'];
unset($d['color']);
$ret[$id] = $d;
$ret[$id]['color'][] = $color;
}else{
$ret[$id]['color'][] = $d['color'];
}
}
return $ret;
}
$data = regroup_color($data);
echo json_encode($data)
...
Or you could just...
make the query 2 part, first is for get all items, second is for get the colors for it
...
$query = "SELECT * FROM items";
// get the data here using query above
$data = {{result of query}};
foreach($data as $i => $d){
$id = $d['id'];
$query = "SELECT * FROM item_color JOIN colors ON item_color.color_id = colors.id";
// get the data here using query above
$colors = {{result of query}};
foreach($colors as color){
$data[$i]['color'][] = $color['name'];
}
}
echo json_encode($data)
...
i wanted to add also category so this is what i came with
function regroup_color($data = array(),$data2 = array()){
// array that will hold our data and we will return it later
$ret = array();
// fetch the data as d
foreach($data as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$color = $d['color'];
unset($d['color']);
//save all the item data
$ret[$id] = $d;
// add color to color array
$ret[$id]['color'][] = $color;
}else{
// if wa alredy did all the above things just keep adding colors to color array
$ret[$id]['color'][] = $d['color'];
}
}
foreach($data2 as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$category = $d['category'];
unset($d['category']);
$ret[$id] = $d;
$ret[$id]['category'][] = $category;
}else{
$ret[$id]['category'][] = $d['category'];
}
}
return $ret;
}
result :
"22": {
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
"black",
"white",
"pink",
"red",
"yellow"
],
"category": [
"buttom",
"hats",
"shoes"
]
}
I need to generate the following JSON from a PHP loop and SQL DB but I'm having trouble:
[
{
"ItemName": "Websites1",
"Websites1": [
{
"0": "1",
"ID": "1",
"1": "Essential",
"WebsiteName": "Essential 1",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 1",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 1",
"2": "SO",
"WebsiteCode": "SO"
}
]
},
{
"ItemName": "Websites2",
"Websites2": [
{
"0": "1",
"ID": "1",
"1": "Essential Ibiza",
"WebsiteName": "Essential 2",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 2",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 2",
"2": "SO",
"WebsiteCode": "SO"
}
]
}
]
I have the relevant data being returned from the DB into PHP fine but I can't work out how to generate the relevant key value pairs and nesting using PHP loops. The code I have so far is:
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json = array();
while ($row = $this->db->row_read($rs)) {
$json["ID"] = $row["ID"];
$json["SelectText"] = $row["SelectText"];
$json["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2 = array();
while ($row = $this->db->row_read($rs)) {
$json2["ID"] = $row["ID"];
$json2["SelectText"] = $row["SelectText"];
$json2["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I'm obviously doing something very wrong as I only end up with one row for each query. The key value pairs are being overwritten with each loop. Also the nesting isn't correct. Sorry for such a dumb question but I've been trying to figure this out from info online and am stuck.
Thanks,
Noon.
EDIT - Managed to fix this using the annswer provided by Anushil Nandan below but the PHP needed a few extra tweaks to get the required format as folows:
// -----------------------------------------------------------------------------------------------
// BANNERMANGEMENTFORM
function bannerManagementJson($JsonItem) {
$this->db->connect();
$response = array();
//Generate Websites drop-down
$SqlStr = "SELECT WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Websites',1);
//Generate Clients drop-down
$SqlStr = "SELECT ClientName AS SelectText, ID AS SelectValue FROM Banners_BannerClients ORDER BY ClientName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Clients',2);
return json_encode($response);
}
// -----------------------------------------------------------------------------------------------
// RETRIEVEFORMELEMENTJSON
function retrieveFormElementJson($SqlStr,$ElementName,$SelectListNo) {
$this->db->sql = $SqlStr;
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json = array();
while ($row = $this->db->row_read($rs)) {
$json[] = $row;
}
$arrayResponse = array("ItemName"=>$ElementName, "SelectList" . $SelectListNo=>$json);
}
return $arrayResponse;
}
your array is being overridden every time it's entering while loop
try:
$json1[] = array();
$json2[] = array();
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json[] = array();
while ($row = $this->db->row_read($rs)) {
$json[]["ID"] = $row["ID"];
$json[]["SelectText"] = $row["SelectText"];
$json[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2[] = array();
while ($row = $this->db->row_read($rs)) {
$json2[]["ID"] = $row["ID"];
$json2[]["SelectText"] = $row["SelectText"];
$json2[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I have two arrays which i want to merge and map the values together where it's id's are same . The problem is when i use array_merge function it only merges two arrays and resulting json is does not fit my model in android.
Here is php function :-
public function getfromorders(){
$sql = 'SELECT * FROM p_orders';
$query = $this -> conn -> prepare($sql);
$query -> execute(array());
$pro1=array();
$orders =array();
while($data = $query -> fetch(PDO::FETCH_OBJ))
{
$orders[] = $data;
$pro1[] = $data -> p_id;
}
$pro=array();
foreach ($pro1 as $id0) {
$sql = 'SELECT * FROM products WHERE p_id = :p_id';
$query2 = $this -> conn -> prepare($sql);
$query2 -> execute(array(':p_id' => $id0));
while($products = $query2 -> fetch(PDO::FETCH_OBJ))
{
$pro[] = $products;
}
}
return array_merge($pro,$orders);
}
Here is resulting json :-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0"
},
{
"email": "7827789246",
"p_id": "4",
"noi": "1",
"order_id": "36"
},
{
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
I want that resulting json should merge the (p_id,email,noi ,order_id) with the (p_id,p_name,p_info......) without changing the mysql database . Is there a way to achieve this?
Here is my expected json:-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0",
"email": "7827789246",
"noi": "1",
"order_id": "36"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0",
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
This is how you can construct your JSON:
while($products = $query2 -> fetch(PDO::FETCH_OBJ)) {
$newElement = array();
foreach($products as $key => value) {
if ($key !== "p_id") {
$newElement[$key] = $value;
}
}
if (!isset($pro[$products["p_id"]])) {
$pro["p_id"] = array();
}
$pro["p_id"][]=$newElement;
}
Note that to avoid duplicating p_id, I have used it as a key. Each key is associated with an array of items.
I'm starting out to learning php and I wrote 2 queries to fetch data from two tables.
Currently, these are my tables:
food_vendors
ID Name Description
-----------------------------
1 Vendor 1 testing
2 Vendor 2 testing
3 Vendor 3 testing
food_vendor_menu
ID VENDOR_ID FOOD_NAME
-----------------------------
1 1 Food 1
2 1 Food 2
3 2 Food 3
4 2 Food 4
5 3 Food 5
Each vendor_id in food_vendor_menu corresponds to the id in food_vendors. Therefore, Vendor 1 would have 2 food items, as well as Vendor 2, while Vendor 3 only has 1 food item.
Currently, I'm making 2 queries and looping through them like so:
$sql = "select * from food_vendors";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from food_vendor_menu where vendor_id=" .$row['id']. "" ;
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
$menuStrings = array();
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$menuStrings[$indexnew] = array("id" => $rownew['id'], "food_name" => $rownew['food_name']);
++$indexnew;
}
}
echo '"item'.$index.'":';
echo json_encode(array("id" => intval($row['id']), "name" => $row['name'], "description" => $row['description'], "menu_items" =>$menuStrings));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }';
This produces the following output:
{
"item1": {
"id": 1,
"name": "Vendor 1",
"description": "testing":,
"menu_items": {
"1": {
"id": "1",
"food_name": "Food 1"
},
"2": {
"id": "2",
"food_name": "Food 2"
}
}
},
"item2": {
"id": 2,
"name": "Vendor 2",
"description": "testing"
"menu_items": {
"1": {
"id": "3",
"food_name": "Food 3"
},
"2": {
"id": "4",
"food_name": "Food 4"
}
}
},
"item3": {
"id": 3,
"name": "Vendor",
"description": "testing",
"menu_items": {
"1": {
"id": "5",
"food_name": "Food 5",
}
}
}
}
However, I don't believe this is the best way, and I like to produce the same output using only one query, so upon research, I try to learn and replaced the above code with the following, joining the 2 tables together:
$sql = "select * from food_vendor_menu s join food_vendors t on t.id=vendor_id" ;
$q = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
while($row = mysqli_fetch_assoc($q))
{
if (isset( $row['vendor_id'] ) )
{
$index = 'item'.$row['vendor_id'].'';
$jsonData[$index] = $row;
unset( $jsonData[$index]['food_name'] );
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
}
}
echo json_encode($jsonData);
The result of the output:
{
"item1": {
"id": "1",
"vendor_id": "1",
"name": "Vendor 1",
"description": "testing",
"menu_items": "Food 1"
},
"item2": {
"id": "2",
"vendor_id": "2",
"name": "Vendor 2",
"description": "testing",
"menu_items": "Food 3"
},
"item3": {
"id": "3",
"vendor_id": "3",
"name": "Vendor 3",
"description": "testing",
"menu_items": "Food 5"
}
}
I know this is the better approach and more efficient, but as you can see from the output above, the menu_items array for Vendor 1 only has Food 1, but no Food 2. The same issue with the other 2 vendors. Also, I need to append the vendor_id to each menu item, not just food name.
I know where the issue is, I just don't know how to fix it, due to my limited knowledge of php at the moment.
Can someone assist?
UPDATE:
Following Joey's suggestion, I replaced:
$jsonData[$index] = $row
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
with:
if ( !isset( $jsonData[$index] ) )
{
$jsonData[$index] = $row;
$jsonData[$index]['menu_items'] = array();
}
array_push($jsonData[$index]['menu_items'], $row['food_name']);
I get the following output:
"item1": {
"id": "1",
"name": "Vendor 1",
"description": "testing",
"menu_items": ["Food 1", "Food 2"]
}
However, I need to make each Food 1, Food 2, an array itself because I need to associate other data to each food item, like id, food price, etc.
$sql = "select * from food_vendor_menu s join food_vendors t on t.id=vendor_id";
...
$jsonData[$index] = $row
...
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
Should something like:
$sql = "select s.id as food_id, s.food_name, s.vendor_id, t.name, t.description from food_vendor_menu s join food_vendors t on t.id=vendor_id";
...
if (!isset($jsonData[$index])) {
$jsonData[$index] = $row;
unset( $jsonData[$index]['food_id'], $jsonData[$index]['food_name'] );
$jsonData[$index]['menu_items'] = array();
}
array_push($jsonData[$index]['menu_items'],
array('id'=>$row['food_id'], 'food_name'=>$row['food_name']));
Query:
$sql = "
SELECT
t.*,
GROUP_CONCAT(CONCAT(s.id, '%%',s.food_name) SEPARATOR '||') as menu_items
FROM
food_vendor_menu s
JOIN
food_vendors t
ON
t.id=vendor_id
GROUP BY
s.vendor_id
";
Php processing
//create an array
$jsonData = array();
$count = 1;
while($row = mysqli_fetch_assoc($q))
{
//lets place the row...
$jsonData['item'.$count] = $row;
//lets edit the menu_items by exploding it....
$menu_items = explode('||', $row['menu_items']);
$jsonData['item'.$count]['menu_items'] = [];
foreach($menu_items as $food_count => $food)
{
list($menu_id, $food_name) = explode('%%', $food);
$menu_item = (object)['id'=>$menu_id, 'food_name'=>$food_name];
$jsonData['item'.$count]['menu_items'][($food_count+1)] = $menu_item;
}
$count++;
}
echo json_encode($jsonData); //output it as a JSON encoded data...
I think its better that the menu_items is represented in array form (enclosed in []) rather than objects (enclosed in {}).
Hello I have this php code for printing json
<?php
include('databaseconnect.php');
$sql = "SELECT product_id,product_name FROM products WHERE product_id='1'";
$result = $conn->query($sql);
$sql2 = "SELECT GROUP_CONCAT(ss.Name,':',sv.value_s ) as Specifications FROM specifications ss, specification_value sv WHERE sv.specification_ID = ss.specification_ID AND sv.product_id = '1'";
$fetch = $conn->query($sql2);
$sql3 = "select GROUP_CONCAT(v.name,':',vv.value) as variants from variant v,variant_value vv where v.variant_id=vv.variant_id and product_id='1'";
$fetch1 = $conn->query($sql3);
$json['products'] = array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$json['products'] = $row;
}
$json['products']['specification'] = array();
while ($row = mysqli_fetch_assoc($fetch)){
$specification_array = explode(',', $row["Specifications"]);
$speci_array = array();
foreach($specification_array as $spec){
$spec = explode(':',$spec);
$speci_array[$spec[0]] = $spec[1];
}
$json['products']['specification'] = $speci_array;
//array_push($json['products'],$row_temp);
}
$json['products']['specification']['variants'] = array();
while ($row = mysqli_fetch_assoc($fetch1)){
$variants_array = explode(',', $row["variants"]);
$vari_array = array();
foreach($variants_array as $var){
$var = explode(':',$var);
$vari_array[$var[0]] = $var[1];
}
$json['products']['specification']['variants'] = $vari_array;
//array_push($json['products'],$row_temp);
}
echo Json_encode($json);
?>
and output of this is
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": {
"size": "long"
}
}
}
}
but in this i have one more value for variant i.e.
"size":"small" and that is not showing up.
sorry for bad English please ask me for any clarification before answering
my desired output
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": {
"size": "small"
"size": "long"
}
}
}
}
You can't add same key size twice. The previous key gets overwritten by later.
Since you are repeating the key size again the values are being overwritten. Pass all the required values which are belonging to the same Key in an array.
yes you cant use same key name ..
you can get like
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": [{"size": "small"},{"size": "long"}]
}
}
}
You can do '$vari_array[$var[0]][] = $var[1];' now the size is multidimensional array.
as shown by https://stackoverflow.com/users/1993125/wisdmlabs in comments