将PHP/MySQL数组编码为JSON时出现问题
我在MySQL中有以下表格:将PHP/MySQL数组编码为JSON时出现问题,php,mysql,sql,json,Php,Mysql,Sql,Json,我在MySQL中有以下表格: recipe: id_recipe (PKey), name_recipe, description url_pic: id_img, url_img, id_recipe (FKey) 使用PHP,我试图获得JSON,其中包含每个配方,以及图片的URL和数组。我的问题是配方2的图片数组包含两个配方的图片!我是个初学者,我找不到问题出在哪里。下面是我想要的JSON、我的PHP代码和我实际得到的JSON: 所需的JSON: PHP: $sql=选择id\u配方、名称
recipe: id_recipe (PKey), name_recipe, description
url_pic: id_img, url_img, id_recipe (FKey)
使用PHP,我试图获得JSON,其中包含每个配方,以及图片的URL和数组。我的问题是配方2的图片数组包含两个配方的图片!我是个初学者,我找不到问题出在哪里。下面是我想要的JSON、我的PHP代码和我实际得到的JSON:
所需的JSON:
PHP:
$sql=选择id\u配方、名称\u配方、说明
从配方;
$result=$conn->query$sql;
如果$result->num_rows>0{
而$row=$result->fetch\u assoc{
$data['recipe']=$row;
$sql2=选择id\u url,url
从url_img作为u
其中u.id_recipe='$row[id_recipe]';
$result2=$conn->query$sql2;
如果$result2->num_rows>0{
而$row2=$result2->fetch_arrayMYSQL_ASSOC{
$array[]=$row2;
}
$data['pictures']=$array;
}
$all[]=$data;
}
标题'Content-Type:application/json';
echo json_encode$all,json_UNESCAPED_UNICODE;
}
实际JSON:
[
{
录像带:{
配方:1,
配方名称:。。,
描述:。。。
},
图片:[
{
id_url:1,
url:配方1的图片1
},
{
id_url:2,
url:配方1的图片2
}
]
},
{
录像带:{
配方:2,
菜谱名称:。。。。,
描述:。。。。
},
图片:[
{
id_url:1,
url:配方1的图片1
},
{
id_url:2,
url:配方1的图片2
},
{
id_url:3,
url:配方2的图片1
},
{
id_url:4,
url:配方2的图片2
}
]
}
]
在每次重新设置中重置阵列
$result2 = $conn->query($sql2);
$array = []; // Add this line
if($result2->num_rows > 0){
$result2 = $conn->query($sql2);
$array = []; // Add this line
if($result2->num_rows > 0){