Create parent child relation JSON tree - php

This is my code I have three table posts table, comments table, and likes table. I have a left joined all three tables with postid common in all three tables. I'm getting all data perfectly but I'm getting repeating data of postdata (ex: Postid=1) I don't want that. My problem is getting repeating data of Postdata (ex: Postid=1) I want to make a parent of Postdata where postsdata=1 and I want to insert all data into parent
<?php
include "../dcon.php";
$sql = "select * FROM posts left join comments on comments.Cpostid=posts.PostId left join likes on likes.postid=posts.PostId";
$query=mysqli_query($mysqli,$sql);
$result = mysqli_num_rows($query);
$menus=array();
for($i=0; $i<$result; $i++){
$row = mysqli_fetch_all($query,MYSQLI_ASSOC);
foreach($row as $index => $row ){
$menus[]=[
'PostId'=>$row['PostId'],
'PostVideo'=>$row['PostVideo'],
'PostDesc'=>$row['PostDesc'],
'PostImage'=>$row['PostImage'],
'PostedBy'=>$row['PostedBy'],
'UserName'=>$row['UserName'],
'Status'=>$row['Status'],
'PostParent'=>$row['PostParent'],
'likes'=>$row['likes'],
'comments'=>[
$index => [
'commentsid'=>$row['commentsId'],
'comments'=>$row['comments'],
'Cpostid'=>$row['Cpostid'],
'time'=>$row['time'],
],],
'likes'=>[
$index =>[
'Likeid'=>$row['Lid'],
'dislikes'=>$row['dislikes'],
'postid'=>$row['postid'],
'userid'=>$row['userid'],
]]
];
}
}
echo json_encode($menus,JSON_PRETTY_PRINT);
?>
My output was below:
[
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "khan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "2",
"comments": "good workouts",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "20",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "26",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "3",
"PostVideo": null,
"PostDesc": "this is an image of chicken",
"PostImage": "post.jpg",
"PostedBy": "khan",
"UserName": null,
"Status": "0",
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
];
I want my output like below:
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes":
'0':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'1':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'2':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'3':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments":
'0':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'1':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'2':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'3':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}

Hmm... At first I thought that your loops were the problem, and you misunderstood the behavior. But then I saw your "i want my output like below", and that didn't made sense, specifically you wanting duplicate likes/comments.
First, the loops: a for loop and an inner foreach loop. The for loop iterates over the number of results. The inner foreach loop iterates over all the results. So if we have 6 results, instead of only iterating 6 times, we iterate 36 times (6 result count x 6 results).
We actually need only 1 loop:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $index => $row) {
$menus[] = [
...
];
}
Next, we avoid duplicate posts by indexing the $menus with PostId. If the PostId does not yet exist in $menus, we insert the post; otherwise we just append the like/comment:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
$menus[$row['PostId']]['comments'][] = [
...
];
$menus[$row['PostId']]['likes'][] = [
...
];
}
If for some reason you don't want the $menus indexed by PostId, we can just call array_values() after the loop to re-index it with zero-based sequential integer:
foreach (...) { ... }
$menus = array_values($menus);
As for the duplicate likes/comments, you were explicit about it. But just in case you actually want non-duplicate, we can also index them by their Likeid and commentsid, and insert/ignore as necessary:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
if (!isset($menus[$row['PostId']]['comments'][$row['commentsid']])) {
$menus[$row['PostId']]['comments'][$row['commentsid']] = [
...
];
}
if (!isset($menus[$row['PostId']]['Likes'][$row['Lid']])) {
$menus[$row['PostId']]['Likes'][$row['Lid']] = [
...
];
}
}
And if we also don't want the comments/likes indexed by commentsid/Lid, we can call array_values() on them as well:
foreach (...) { ... }
$menus = array_values($menus);
foreach ($menus as &$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
}
unset($menu);
// Or
array_walk($menus, function (&$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
});

Related

nested json data with parent

<?php
include "../dcon.php";
$sql = "select * FROM posts left join comments on comments.Cpostid=posts.PostId left join likes on likes.postid=posts.PostId";
$query=mysqli_query($mysqli,$sql);
$result = mysqli_num_rows($query);
$menus=array();
for($i=0; $i<$result; $i++){
$row = mysqli_fetch_all($query,MYSQLI_ASSOC);
foreach($row as $index => $row ){
$menus[]=[
'PostId'=>$row['PostId'],
'PostVideo'=>$row['PostVideo'],
'PostDesc'=>$row['PostDesc'],
'PostImage'=>$row['PostImage'],
'PostedBy'=>$row['PostedBy'],
'UserName'=>$row['UserName'],
'Status'=>$row['Status'],
'PostParent'=>$row['PostParent'],
'likes'=>$row['likes'],
'comments'=>[
$index => [
'commentsid'=>$row['commentsId'],
'comments'=>$row['comments'],
'Cpostid'=>$row['Cpostid'],
'time'=>$row['time'],
],],
'likes'=>[
$index =>[
'Likeid'=>$row['Lid'],
'dislikes'=>$row['dislikes'],
'postid'=>$row['postid'],
'userid'=>$row['userid'],
]]
];
}
}
echo json_encode($menus,JSON_PRETTY_PRINT);
?>
**
this is my code i have three table posts table, comments table, and likes table. i have a left joined all three tables with postid common in all three tables. im getting all data perfectly but im getting repeating data of postdata (ex:Postid=1) i dont want that.
my problem is getting repeating data of Postdata(ex:Postid=1) i want to make a parent of Postdata where postsdata=1 and i want to insert all data into parent
**
[
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "khan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "2",
"comments": "good workouts",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "20",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "26",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "3",
"PostVideo": null,
"PostDesc": "this is an image of chicken",
"PostImage": "post.jpg",
"PostedBy": "khan",
"UserName": null,
"Status": "0",
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
];

how to do pagination complex array in cakephp rest-api?

CakePHP Rest-API pagination in an array of array. Like, containable model pagination in CakePHP for reducing API load.
Some existing code :
$this->request->data['page'];
$data = $this->Model1->find('all',array(
'contain' => array('Model2'),
'fields' => array(),
'conditions' => array('Model1.status' => 1 )
));
Below API response and I want to paginate in ProductUser array because when lots of product load at one-time app will be hang. It's possible or any other way to reduce data load in CakePHP.
API Response :
"status": true,
"message": "Available devices!",
"data": [
{
"id": "6",
"name": "Television",
"parent_id": "0",
"image": "",
"status": "1",
"created": "2019-06-10 15:22:44",
"modified": "2019-06-10 15:22:44",
"ProductUser": [ //Paginate this array
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
},
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
}
]
}]

How to access child array key value pair in Laravel controller?

My response code :
Shpping : [
{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [
{
"id": "1",
"cname": "basic",
"base_id": 44
},
{
"id": "2",
"cname": "Shirt",
"base_id": 177444
},
{
"id": "3",
"cname": "Pants",
"base_id": 444
}
]
}
];
I want to access base_id of of every object in child array 'minicomp' whose parent is 'Shipping'. How can I access it?
First convert your json into array using json_decode().Like this..
$json =<your json>;
$array = json_decode($json,true);
Then
echo $array['Shpping '][0]]['minicomp'][0]['id'];//outputs 1
Example:
<?php
$json = '[{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [{
"id": "1",
"cname": "basic",
"base_id": 44
}, {
"id": "2",
"cname": "Shirt",
"base_id": 177444
}, {
"id": "3",
"cname": "Pants",
"base_id": 444
}]
}]';
$array = json_decode($json,true);
//print_r($array);
$minicomp = $array[0]['minicomp'];
echo $minicomp[0]['id'];
echo $minicomp[1]['id'];
?>
UPDATE
For getting all ids.Without defining indexes.Use foreach loop:
foreach($minicomp as $key=>$value){
echo $minicomp[$key]['id']."<br/>";
}

Generate html according to category through php or jquery

I am facing a problem to show html like this from my webservice.
In database I have two tables product and product_category both have relation on id like product.category_id=product_category.id. and I am using mysqli and php.
PHP:
function get_product_by_category(){
$query = "SELECT * from product p JOIN product_category pc ON pc.id = p.category_id";
$result = $this->fetch_all($query);
if($result>0){
$data = json_encode($result);
}else{
$data = json_encode(array("status"=>false));
}
echo $data;
}
Json:
[
{
"id": "1",
"category_id": "1",
"product_name": "Plain Shoes",
"product_price": "10000",
"product_discount": "20",
"valid_upto": "2015-10-10",
"size": "Small,Medium",
"color": "Brown,Black",
"image": "1,2,3",
"caption": "behtreen",
"description": "alal",
"details": "lush",
"created_date": "2015-10-31 22:14:44",
"category_name": "Shoes"
},
{
"id": "2",
"category_id": "2",
"product_name": "Kurta",
"product_price": "2000",
"product_discount": "10",
"valid_upto": "2015-10-10",
"size": "Small",
"color": "Blue,Sky",
"image": "1,2,3",
"caption": null,
"description": null,
"details": null,
"created_date": "2015-10-31 22:56:53",
"category_name": "Dress"
},
{
"id": "1",
"category_id": "1",
"product_name": "Shoes",
"product_price": "9000",
"product_discount": "40",
"valid_upto": "2015-10-10",
"size": null,
"color": null,
"image": null,
"caption": null,
"description": null,
"details": null,
"created_date": "2015-10-31 23:07:46",
"category_name": "Shoes"
}
]
Now i want this json to create html like my image.
You should generate html, use something like this:
foreach ($data as $product){
echo '<div class="product_name">' . $product['product_name'] . '</div>';
echo '<div class="product_discount">' . $product['product_discount'] . '</div>';
if (isset($product['size'])) {
echo '<div class="size">' . $product['size'] . '</div>';
}
// all other html elements that you need.
}

Print value from inside an object

I have really have troubles trying to work out why this is not working, and it seems like it should be easy, but just cannot seem to get it.
All I am looking to do is grab the sku field (which is VBP-01 below).
{
"variants": [
{
"id": 2314578,
"created_at": "2014-07-29T07:22:18.921Z",
"updated_at": "2015-05-21T15:42:42.136Z",
"product_id": 1188647,
"default_ledger_account_id": null,
"buy_price": "124.0",
"committed_stock": "0",
"incoming_stock": "3",
"composite": false,
"description": null,
"is_online": false,
"keep_selling": false,
"last_cost_price": "124.0",
"manage_stock": true,
"max_online": null,
"moving_average_cost": "124",
"name": "Lanparte battery pinch VBP-01",
"online_ordering": false,
"opt1": null,
"opt2": null,
"opt3": null,
"position": 1,
"product_name": "Lanparte V-Mount Battery Pinch",
"product_status": "active",
"product_type": null,
"retail_price": "0.0",
"sellable": true,
"sku": "VBP-01",
"status": "active",
"stock_on_hand": "1",
"supplier_code": "VBP-01",
"taxable": true,
"upc": null,
"weight": null,
"wholesale_price": "0.0",
"image_ids": [],
"variant_prices": [
{
"price_list_id": "buy",
"value": "124.0"
},
{
"price_list_id": "retail",
"value": "0.0"
},
{
"price_list_id": "wholesale",
"value": "0.0"
}
],
"locations": [
{
"location_id": 16377,
"stock_on_hand": "1",
"committed": null,
"incoming": "3",
"bin_location": null,
"reorder_point": 3
}
],
"prices": {
"buy": "124.0",
"retail": "0.0",
"wholesale": "0.0"
},
"stock_levels": {
"16377": "1.0"
},
"committed_stock_levels": {},
"incoming_stock_levels": {
"16377": "3.0"
}
}
],
"meta": {
"total": 1
}
}
Currently I using the following code with no luck
$url = "https://api.tradegecko.com/variants?sku=VBP-01";
$data = file_get_contents($url, false, $context);
$json = json_decode($data);
print $json->{'variant'}->{'sku'};
What I am doing wrong?
Just
echo $json->{'variants'}[0]->{'sku'};
In a loop
foreach ($json->variants as $variants) {
echo $variants->sku;
}

Categories