【问题标题】:dynamic json file from mysql data arrays using php loops使用 php 循环从 mysql 数据数组获取动态 json 文件
【发布时间】:2019-05-28 21:30:24
【问题描述】:

尝试从 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
  • 我建议在 SQL 中使用 join 来获取结果而不是两个 SQL 语句
  • 顺便说一句:在不知道数据库中的数据的情况下,您为什么期望这个结果非常不清楚
  • 我的道歉。项目行是这个 $items[] = $row['item_name'];

标签: php mysql arrays json loops


【解决方案1】:

您需要将$items[1] = $row[1]; 更改为$item_name = $row[1]$items[] = $row; 更改为$items[$item_name] = $row;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多