我在 MySQL 中有以下表:
recipe: id_recipe (PKey), name_recipe, description
url_pic: id_img, url_img, id_recipe (FKey)
使用 PHP,我尝试获取包含每个 recipe
及其图片 url(数组)的 JSON。我的问题是食谱 2 的图片数组包含两个食谱的图片!我是初学者,找不到问题出在哪里。我在下面包含了我想要的 JSON、我的 PHP 代码和我实际获得的 JSON:
所需的 JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
PHP:
$sql = "SELECT id_recipe,name_recipe,description
FROM recipe";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['recipe'] = $row;
$sql2= "SELECT id_url,url
FROM url_img as u
WHERE u.id_recipe = '$row[id_recipe]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0){
while($row2 = $result2->fetch_array(MYSQL_ASSOC)) {
$array[] = $row2;
}
$data['pictures'] = $array;
}
$all[] = $data;
}
header('Content-Type: application/json');
echo json_encode($all,JSON_UNESCAPED_UNICODE);
}
实际 JSON:
[
{
"recette": {
"id_recipe": "1",
"name_recipe": "..",
"description":"..."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
}
]
},
{
"recette": {
"id_recipe": "2",
"name_recipe": "....",
"description": "...."
},
"pictures": [
{
"id_url": "1",
"url": "picture 1 of recipe 1"
},
{
"id_url": "2",
"url": "picture 2 of recipe 1"
},
{
"id_url": "3",
"url": "picture 1 of recipe 2"
},
{
"id_url": "4",
"url": "picture 2 of recipe 2"
}
]
}
]
最佳答案
在每次迭代中重置数组
$result2 = $conn->query($sql2);
$array = []; // Add this line
if($result2->num_rows > 0){
关于php - 将 PHP/MySQL 数组编码为 JSON 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572366/