我试图将三个表中的json数据以一对多关系映射到彼此,并希望以这种格式显示这些数据
{
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$
}
},
{
},
...
]
}
在这个“品牌”“product_Description”中从一张桌子和“耐克”“非常好” 从第二个表。 我正在写这个php文件来实现这个
<?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);
?>
但我得到这样的输出
[
[
{
"brand": "Nike"
},
{
"product_Description": "very good"
}
]
]
答案 0 :(得分:0)
而不是以下代码:
$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);
如上所述,你必须在一个stinrg中添加产品描述,你可以通过以下方式实现: $ row_array = array(); // $ row_array [&#39; product_name&#39;] = $ row [&#39; product_name&#39;];
$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