I am trying to get json data from three tables mapped to each other in one to many relationship and want to display those data in this format
{
products: [
{
"product_id": 121,
"name": "Nike Fusion",
"type": "Running Shoe",
"brand": "Nike",
"product_Description": "very good",
"size": {
"value": "small"
"price": 200$
},
"weight": {
"value": "100gm"
"price": 100$
}
},
{
},
...
]
}
in this the "brand" "product_Description" from one table and "Nike" "very good" from second table. i am writing this php file to achieve this
<?php
include('db_connection.php');
$result = mysql_query("select product_name,product_id from products where product_id='1' ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
// $row_array['product_name'] = $row['product_name'];
$qus_pk = $row['product_id'];
$option_qry = mysql_query("select ss.Name,sv.value_s from specifications ss,specification_value sv where sv.specification_ID=ss.specification_ID and sv.product_id =$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array[] = array(
$opt_fet['Name'] => $opt_fet['value_s'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
?>
but i am getting output like this
[
[
{
"brand": "Nike"
},
{
"product_Description": "very good"
}
]
]
instead of your following code :
$row_array = array();
// $row_array['product_name'] = $row['product_name'];
$qus_pk = $row['product_id'];
$option_qry = mysql_query("select ss.Name,sv.value_s from specifications ss,specification_value sv where sv.specification_ID=ss.specification_ID and sv.product_id =$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array[] = array($opt_fet['Name'] => $opt_fet['value_s'],);
}
//array_push($json_response, $row_array);
for displying like above you have to add product description in one stinrg and you can achive by following: $row_array = array(); // $row_array['product_name'] = $row['product_name'];
$qus_pk = $row['product_id'];
$product_desc = '';
$brand_name = '';
$option_qry = mysql_query("select ss.Name,sv.value_s from specifications ss,specification_value sv where sv.specification_ID=ss.specification_ID and sv.product_id =$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
//$row_array[] = array(
$opt_fet['Name'] => $opt_fet['value_s'], );
$product_desc .=$opt_fet['value_s'].",";
$brand_name .= $opt_fet['Name'].",";
}
$product_desc = rtrim($product_desc);
$brand_name = rtrim($brand_name);
$row_array['product_Description'] = $product_desc;
$row_array['brand'] = $brand_name;
array_push($json_response, $row_array); //push the values in the array