I want to create a JSON format from 3 mysql tables using PHP. Below is my table:
To create a JSON format from these 3 tables I am using this code:
<?php
ini_set('display_errors', 'Off');
$user = "root";
$password = "";
$database = "mydb";
$conn = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$sql = "SELECT model_id FROM 1Model";
$sqlRun = mysqli_query($conn , $sql);
$json = array();
$role_model = mysqli_num_rows($sqlRun);
if($role_model > 0){
$i = 0;
while($row = mysqli_fetch_array($sqlRun)){
$row_array= array();
$model_id = $row['model_id'];
$json[$i]['model_id'] = $row['model_id'];
$role_qry = mysqli_query($conn, "SELECT id_cat, cat_name, model_id FROM 1Category WHERE model_id= $model_id");
while($role_fet = mysqli_fetch_array($role_qry)){
$json[$i]['id_cat']['id_cat'] = $role_fet['id_cat'];
$json[$i]['cat_name']['cat_name'] = $role_fet['cat_name'];
$cat_array = array();
$cat_pk = $role_fet['id_cat'];
$test_query = mysqli_query($conn, "SELECT id_item, item_name, id_cat FROM 1Item WHERE id_cat = $cat_pk");
$j = 0;
while($test_fet = mysqli_fetch_array($test_query)){
$json[$i]['item_list']['items'][$j] = array('item_name' => $test_fet['item_name']);
$j++;
}
}
$i++;
}
}
header('Content-type: text/javascript');
echo json_encode($json, JSON_PRETTY_PRINT);
?>
My expected result is json object will filter based on the model name and category name, something like below:
[
{
"model_id": "1",
"cat_name": {
"cat_name": "Box Medium"
"item_list": {
"items": [
{
"item_name": "Box Medium Orange"
},
{
"item_name": "Box Medium Purple"
},
{
"item_name": "Box Medium White"
},
{
"item_name": "Box Medium Grey"
}
]
}
},
},
{
"model_id": "2",
"id_cat": {
"id_cat": "6"
},
"cat_name": {
"cat_name": "Square Large"
}
},
{
"model_id": "3"
}
]
But I don't know why my result children values not filtered based on parent id.
Right now the code encode json as result below:
[
{
"model_id": "1",
"id_cat": {
"id_cat": "3"
},
"cat_name": {
"cat_name": "Box Large"
},
"item_list": {
"items": [
{
"item_name": "Box Medium Orange"
},
{
"item_name": "Box Medium Purple"
},
{
"item_name": "Box Medium White"
},
{
"item_name": "Box Medium Grey"
}
]
}
},
{
"model_id": "2",
"id_cat": {
"id_cat": "6"
},
"cat_name": {
"cat_name": "Square Large"
}
},
{
"model_id": "3"
}
]
Anyone can help me on this, tried to find on the web but unlucky. What I am trying to do is to get a json format hierarchical, model=parent, category=subparent, item=child. Thanks for any helps
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 have four tables, ALBUM,ARTIST,SONG,GENRES
ALBUM (ID(PK),ALBUM_NAME,ARTIST_ID(FK),GENRES_ID(FK),ALBUM_POSTER)
SONG (ID(PK),SONG_NAME,ALBUM_ID(FK),ARTIST_ID(FK),SONG_LOCATION)
ARTIST (ID(PK),ARTIST_NAME)
GENRES (ID(PK), GENRES_NAME)
I have created the bellow php file in order to create json file as "desired output" shows, but I have got "actual output" as bellow shows. All songs from all albums are included in each album "song_detail" section as the actual output shows.
php
$sql = "SELECT DISTINCT ALBUM_ID, ALBUM_NAME,ARTIST_NAME,GENRES_NAME,ALBUM_POSTER "
. "FROM ALBUM,ARTIST,SONG,GENRES "
. "WHERE ALBUM.ID=SONG.ALBUM_ID AND SONG.ARTIST_ID=ARTIST.ID AND GENRES.ID=ALBUM.GENRES_ID";
$result = $db->query($sql);
$response["albums"] = array();
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{ $album = array();
$album["album_id"] = $row["ALBUM_ID"];
$album["album_name"] = $row["ALBUM_NAME"];
$album["artist_name"] = $row["ARTIST_NAME"];
$album["genres_name"] = $row["GENRES_NAME"];
$album["album_poster"] = "http://www.".$row["ALBUM_POSTER"];
$album['song_details'] = array();
$sql2 = "SELECT*"
. " FROM SONG,ALBUM where SONG.ALBUM_ID = ALBUM.ID";
$result2 = $db->query($sql2);
while ($row2 = $result2->fetch_assoc())
{
$album['song_details'][] = array(
'songName' => $row2["SONG_NAME"],
'song_location' => "http://www.".$row2["SONG_LOCATION"]);
}
array_push($response["albums"], $album);
}
$response["success"] = 1;
}
desired output
[
{
"album_name": "Startboy",
"artist_name": "Weeknd",
"genres_name":"R&B",
"album_poster": "www.yyy.storage.x.png",
"songs_details": [{
"title": "False Alarm",
"song_location": "www././../yw.mp3"
},
{
"title": "Reminder",
"song_location": "www././../x.mp3"
}
]
},
{
"album_name": "25",
"artist_name": "Adele",
"genres_name":"",
"album_poster": "www.yyy.storage.a.png",
"songs_details": [{
"title": "Hello",
"song_location": "www././../yy.mp3"
},
{
"title": "I Miss You",
"song_location": "www././../yx.mp3"
}
]
}
]
Actual output
[
{
"album_name": "Startboy",
"artist_name": "Weeknd",
"genres_name":"R&B",
"album_poster": "www.yyy.storage.x.png",
"songs_details": [{
"title": "False Alarm",
"song_location": "www././../yw.mp3"
},
{
"title": "Reminder",
"song_location": "www././../x.mp3"
},
{
"title": "Hello",
"song_location": "www././../yy.mp3"
},
{
"title": "I Miss You",
"song_location": "www././../yx.mp3"
}]
},
{
"album_name": "25",
"artist_name": "Adele",
"genres_name":"",
"album_poster": "www.yyy.storage.a.png",
"songs_details": [{
"title": "False Alarm",
"song_location": "www././../y.mp3"
},
{
"title": "Reminder",
"song_location": "www././../x.mp3"
},
{
"title": "Hello",
"song_location": "www././../yy.mp3"
},
{
"title": "I Miss You",
"song_location": "www././../yx.mp3"
}
]
}
]
When you are selecting the songs, your SQL doesn't limit which album the tracks are from (although it does make sure they match the ALBUM)...
$sql2 = "SELECT*"
. " FROM SONG,ALBUM where SONG.ALBUM_ID = ALBUM.ID";
You need to just pick the SONG records according to the current album...
$sql2 = "SELECT * FROM SONG where ID =".$row["ALBUM_ID"];
You could use prepared statements here, but as this is using a field from another table it can be used - but not essential.
I have the following tables in MySQL:
recipe: id_recipe (PKey), name_recipe, description
url_pic: id_img, url_img, id_recipe (FKey)
Using PHP, I am trying to get JSON which contains every recipe, along with its pictures' urls (an array). My problem is that the pictures array of recipe 2 includes the pictures of both recipes! I'm a beginner and I can't find where the problem is. I've included below the JSON I want, my PHP code, and the JSON I actually get:
Desired JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
PHP:
$sql = "SELECT id_recipe,name_recipe,description
FROM recipe";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['recipe'] = $row;
$sql2= "SELECT id_url,url
FROM url_img as u
WHERE u.id_recipe = '$row[id_recipe]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0){
while($row2 = $result2->fetch_array(MYSQL_ASSOC)) {
$array[] = $row2;
}
$data['pictures'] = $array;
}
$all[] = $data;
}
header('Content-Type: application/json');
echo json_encode($all,JSON_UNESCAPED_UNICODE);
}
Actual JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
},
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
Reset the array in each itteration
$result2 = $conn->query($sql2);
$array = []; // Add this line
if($result2->num_rows > 0){
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.
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.