尝试从 mysql 数据库创建 json 数据,但我在数组循环中遇到问题。
mysql 表:
table item
item_ id item_name p_id
1 item1 1
2 item2 2
table product_info
p_ id size color
1 medium white
2 large red
这是我的代码:
$sql = "SELECT item_id, item_name FROM items";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result)) {
$item_id = $row[0];
$items[] = $row['item_name'];
$sql1 = "SELECT color, size FROM product_info where product_id = '$item_id'";
$result1 = mysqli_query($connect, $sql1);
while($row = mysqli_fetch_assoc($result1) {
$items[] = $row;
}
}
echo json_encode($items);
并输出:
[
"item1",{"color":"white","size":"medium"},
"item2",{"color":"red","size":"large"}
]
我很难分配项目=>信息。
假设我想要的输出将是这样的:
{
"item1":{"color":"white","size":"medium"},
"item2":{"color":"red","size":"large"}
}
我尝试了 PHP 脚本的串联,但编码为 json 时情况变得更糟。 需要您的更正..
最佳答案
您需要将 $items[1] = $row[1];
更改为 $item_name = $row[1]
和 $items[ ] = $row;
到 $items[$item_name] = $row;
关于php - 使用 php 循环从 mysql 数据数组动态生成 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002866/