[英]dynamic json file from mysql data arrays using php loops
try create json data from mysql data base but im having problem in array loops. 尝试从mysql数据库创建json数据,但是在数组循环中出现问题。
mysql tables: 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
here is my code: 这是我的代码:
$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);
and output this: 并输出:
[
"item1",{"color":"white","size":"medium"},
"item2",{"color":"red","size":"large"}
]
Im having a hard time assigning items => info. 我很难分配项目=>信息。
supposedly my desired output will be like this: 据称我想要的输出将是这样的:
{
"item1":{"color":"white","size":"medium"},
"item2":{"color":"red","size":"large"}
}
I tried concatenation on PHP script but its getting worse when encoded to json. 我尝试在PHP脚本上进行串联,但是当编码为json时它会变得更糟。 need your corrections.. 需要您的更正..
You will need to change $items[1] = $row[1];
您将需要更改$items[1] = $row[1];
to $item_name = $row[1]
and $items[] = $row;
到$item_name = $row[1]
和$items[] = $row;
to $items[$item_name] = $row;
到$items[$item_name] = $row;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.