Creating array inside array from mysql data to json - php

I am trying to create json with php from two mysql tables:- Category(unique)- Subcategories or Rights(multiple in same category)But I can't list multiple subcategories under one category. Instead, for every subcategory new set of results is made that contains category data also.
This is php code:
$sql = "SELECT a.id as rid,a.name as rname,a.img as rimg,a.price,b.id as cid,b.name as cname FROM rights a INNER JOIN categories b ON a.category=b.id";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$json_response = array();
while($row = $result->fetch_assoc()) {
$row_array['idCategory'] = $row['cid'];
$row_array['nameCategory'] = $row['cname'];
$row_array['rights'] = array([
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
]);
array_push($json_response,$row_array);
}
echo json_encode($json_response);
}
With this I am getting:
[{
"idCategory": "1",
"nameCategory": "Cat1",
"rights": [{
"idRight": "1",
"name": "Right1 in Cat1",
"price": "10",
"image": "img1.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "2",
"name": "Right1 in Cat2",
"price": "20",
"image": "img2.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "3",
"name": "Right2 in Cat2",
"price": "30",
"image": "img3.jpg"
}]
}]
I tried changing mysql select with GROUP_CONCAT and GROUP BY but then I get data in one row like this:
"rights": [{
"idRight": "2,3",
"name": "Right1 in Cat2,Right2 in Cat2",
"price": "20,30",
"image": "img2.jpg,img3.jpg"
}]
But I need it like this:
[{
"idCategory": "1",
"nameCategory": "Cat1",
"rights": [{
"idRight": "1",
"name": "Right1 in Cat1",
"price": "10",
"image": "img1.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "2",
"name": "Right1 in Cat2",
"price": "20",
"image": "img2.jpg"
},
{
"idRight": "3",
"name": "Right2 in Cat2",
"price": "30",
"image": "img3.jpg"
}]
}]
How to achieve that?

You need to remap your array and then initialize an array for the rights key... so, change your while loop something like this:
$json_response = array();
while($row = $result->fetch_assoc()) {
if (!isset($json_response[ $row['idCategory'] ])) {
$json_response[ $row['idCategory'] ] = [
'idCategory' => $row['idCategory'],
'nameCategory' => $row['nameCategory'],
'rights' => [],
];
}
$json_response[ $row['idCategory'] ]['rights'][] = [
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
];
}
// We want the final result to ignore the keys and to create a JSON array not a JSON object
$data = [];
foreach ($json_response as $element) {
$data[] = $element;
}
echo json_encode($data);
This part of the code $json_response[ $row_array['idCategory'] ] helps to maintain a unique grouping of the data because it creates a hash based on the idCategory. An array can only have one key and since idCategory is always unique we can use that as the key for grouping on.
Then because we now have a hash-based array, we have to create a new array that is a 'real' array for when it is converted to JSON.
You do not want to use GROUP BY or GROUP_CONCAT in this situation.

I revised the code above to fit my needs, but I am having trouble to make another array of that array...
from:
...
$json_response[ $row['idCategory'] ]['rights'][] = [
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
];
to:
$json_response[ $row['regCode'] ]['provinces'][] = $row['provDesc'];
actually this is a follow up question,
how about array inside array of that array...
like this:
[
{
rid: "1",
region: "REGION I", //array 1
provinces: [
{
pid: "128",
province: "ILOCOS NORTE", //array 2
cities[
"Adams", //array 3
"Bacarra"
],
"ILOCOS SUR"
]
},
{
rid: "2",
region: "REGION II",
provinces: [
"BATANES",
"CAGAYAN"
]
}
]

Related

Insert value in array after every index using php

I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);

how I do Multidimensional foreach loop array to json object conversion in php

I am working on the array to JSON object code and want the output using json_encode method.
here is the code
foreach($servicecategory as $servicecategory1) {
$getcat = $objcat->Get_Category($servicecategory1);
$employee = array(
'category_id'=>mysql_real_escape_string($getcat['id']),
'category_name'=>mysql_real_escape_string($getcat['catname']),
'category_image_url'=>"",
'subcategory'=>array()
);
$getsubcat = $objcat->getCategoriesAdminNew($servicecategory1);
foreach($getsubcat as $getsubcat1) {
$getcat = $objcat->Get_Category($getsubcat1['id']);
$employee['subcategory'][]= array(
'category_id'=>mysql_real_escape_string($getcat['id']),
'category_name'=>mysql_real_escape_string($getcat['catname']),
'vendor_products_details' =>array()
);
$getproduct = $objuser->VendorProductDetailsNew2($userinfo['profile_id'],$getcat['id']);
foreach($getproduct as $getproducts){
$getcat = $objcat->Get_Category($getproducts['subcat_id']);
$employee['vendor_products_details'][] = array(
'product_id' => $getproducts['id'],
'product_name' => $getproducts['pname'],
'Price' => $getproducts['price'],
);
}
}
$data[] = $employee;
}
if($userinfo!='') {
$infodatas=array("status"=>"success","vendor_detail"=> array($array1, $data));
$ress=json_encode($infodatas);
echo $ress ;
}
it displays the output like below, which is not the proper format for json out put.
{
"category_id": "1",
"category_name": "Dry Cleaning",
"category_image_url":"",
"subcategory": [
{
"sub_category_id": "4",
"sub_category_name": "Men",
"vendor_products_details": [
]
},
{
"sub_category_id": "5",
"sub_category_name": "Women",
"vendor_products_details": [
]
}
],
"vendor_products_details": [
{
"product_id": "19",
"product_name": "T Shirt",
"Price": "20"
},
{
"product_id": "20",
"product_name": "Top",
"Price": "15"
}
]
},
But I want the output in below format using multiple for each loop.
{
"category_id": "1",
"category_name": "Dry Cleaning",
"category_image_url": "",
"subcategory": [
{
"sub_category_id": "4",
"sub_category_name": "Men",
"vendor_products_details": [
{
"product_id": "19",
"product_name": "T Shirt",
"Price": "20"
},
{
"product_id": "20",
"product_name": "Top",
"Price": "15"
}
]
},
{
"sub_category_id": "5",
"sub_category_name": "Men",
"vendor_products_details": "Women",
"vendor_products_details": [
{
"product_id": "18",
"product_name": "T shirt",
"Price": "15"
},
{
"product_id": "9",
"product_name": "Bedsheet",
"Price": "15"
}
]
}
]
},
same for each main category
Your current foreachloop states that in the get products section it should be added to $employee['vendor_products_details'][], but your explanation states that you want the products to be under your subcategory. This can be achieved by 2 small changes:
foreach($getsubcat as $getsubcat1) {
$getcat = $objcat->Get_Category($getsubcat1['id']);
$employee['subcategory'][$getsubcat1['id']]= array(
'category_id'=>mysql_real_escape_string($getcat['id']),
'category_name'=>mysql_real_escape_string($getcat['catname']),
'vendor_products_details' =>array()
);
$getproduct = $objuser->VendorProductDetailsNew2($userinfo['profile_id'],$getcat['id']);
foreach($getproduct as $getproducts){
$getcat = $objcat->Get_Category($getproducts['subcat_id']);
$employee['subcategory'][$getsubcat1['id']]['vendor_products_details'][] = array(
'product_id' => $getproducts['id'],
'product_name' => $getproducts['pname'],
'Price' => $getproducts['price'],
);
}
}
What is changed:
In your foreachloop with $getsubcat you need to changed the array to:
$employee['subcategory'][$getsubcat1['id']]= array(............);
In your foreachloop with $getproduct you need to change the array to:
$employee['subcategory'][$getsubcat1['id']]['vendor_products_details'][] = array(............);
Doing it this way you vendor product details will be nested in your subcategory with the id used in that specific loop.

Nested JSON Object with array in PHP

I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)

Having trouble building nested JSON with PHP

I am having trouble getting these arrays to nest properly. I am grabbing all the rows from a SQL database and building an array to output in JSON for my crud app. One category has been easy, but the client now wants subcategories and that's when I hit a major wall. I am trying to nest these subcategories into categories. I can do either, but am failing to get them working together. The following is my PHP code:
while ($row = $query->fetch_assoc()) {
$categories[$row['category']][] = array(
$row['subcategory'] => $subcategories[$row['subcategory']][] = array(
'id' => $row['id'],
'item_name' => $row['item_name'],
'description' => $row['description'],
'price' => $row['price'],
),
);
}
foreach ($categories as $key => $value) {
$category_data[] = array(
'category' => $key,
'category_list' => $value,
);
}
foreach ($subcategories as $key => $value) {
$subcategory_data[] = array(
'subcategory' => $key,
'subcategory_list' => $value,
);
}
When I json_encode($category_data) I get the following JSON:
[
{
"category": "Beer",
"category_list": [
{
"Draft Beer": {
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa. An American classic."
}
},
{
"Draft Beer": {
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager"
}
},
{
"Domestic Bottles": {
"id": "9",
"item_name": "Stone IPA",
"description": "India Pale Ale.<em> Escondido, Colo."
}
}
]
},
{
"category": "Wine",
"category_list": [...]
}
]
Which might work, but I would like it to join the like keys (ie: Draft Beer) into the same array. It does do that when I json_encode($subcategory_data) as shown below, but its not separated into categories, just the subcategories.
[
{
"subcategory": "Draft Beer",
"subcategory_list": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
]
},
{
"subcategory": "Red Wine",
"subcategory_list": [
{
"id": "17",
"item_name": "Kendall-Jackson",
"description": "Cabernet Sauvignon, 2010."
},
{
"id": "18",
"item_name": "Sanford",
"description": "Pinot Noir, 2011. Lompoc, Calif"
}
]
},
{
"subcategory": "Domestic Bottles",
"subcategory_list": [
{
"id": "9",
"item_name": "Stone IPA",
"description": "India Pale Ale. Escondido, Colo."
},
{
"id": "10",
"item_name": "Blue Moon",
"description": "Belgian-style Wheat Ale."
}
]
}
]
So my question is why does it merge in the second set of data but not the first. How do I get the subcategory_data into the category_data. Any help id truly appreciated. Below is an example if what I am looking for:
{
"category_name":"Beer",
"category_list" : [
{
"subcategory_name": "Draft Beer",
"subcategory_list": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
}
]
},
{
"category_name":"Wine",
"category_list" : [
{
"subcategory_name": "Red Wine",
"subcategory_list": [...]
}
]
}
Thanks for looking, I am fairly new to PHP and am relying on my javascript skills.
First, try var_dump($categories). You'll see that you're building a rather weird data structure (you have arrays of 1-element arrays...). The following code will build a simpler structure:
$categories[$row['category']][$row['subcategory']][] = array(
'id' => $row['id'],
'item_name' => $row['item_name'],
'description' => $row['description'],
'price' => $row['price'],
);
This will serialize to JSON that's probably acceptable as is:
{
"Beer": {
"Draft Beer": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
],
...
An additional transformation gets the data in the format you asked for:
foreach ($categories as $category_name => $subcategories) {
$subcategory_data = array();
foreach ($subcategories as $subcategory_name => $items) {
$subcategory_data[] = array(
'subcategory_name' => $subcategory_name,
'subcategory_list' => $items
);
}
$category_data[] = array(
'category_name' => $category_name,
'category_items' => $subcategory_data
);
}

Structure JSON output with PHP

I am trying to generate a JSON output from the DATABASE with MySQL.
The result that I want is that I want an array around two matching ID's found in the tabel in the database.
To visualise what I wish to achieve here is my code:
This is my query
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
while($record = mysql_fetch_assoc($result)) {
$rows[] = $record;
}
print json_encode($rows);
This is the JSON result I wish to achieve:
(What I want)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
],
[
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
So, I want the matching ID's (in this case id_flower) put in one array.
This is the result I get:
(What I get)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
},
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
Try this
foreach ($rows as $key => $val) {
$return[$val['id_flower']][] = $val;
}
echo json_encode($return);
Please note I have not tested it.
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
$rows = array();
while($record = mysql_fetch_assoc($result)) {
array_push($rows[$record["id_flower"]], $record);
}
$result = array();
foreach($rows as $k => $v){
array_push($result, $v);
}
echo json_encode($result);
test yourself !

Categories