简体   繁体   English

如何使用Php在JSON中表示一对多关系?

[英]How to represent One-to-Many relationship in JSON using Php?

I have a MySQL table that has two columns customer_id and item_id, 我有一个MySQL表,其中有两列customer_id和item_id,

customer_id can have multiple item_id, (One to many relationships), customer_id可以有多个item_id(一对多关系),

How can I represent/loop through the returned query generate a JSON output (similar to the structure above) ,using MySQL and PHP? 如何使用MySQL和PHP在返回的查询中表示/循环生成JSON输出(类似于上面的结构)?

for example, I want my JSON output to look like this: 例如,我希望我的JSON输出如下所示:

  {
        "data": 
         {
            "customer_id": "10",
            "item_id": " 1"
          },
         {
           "customer_id": "10",
            "item_id": " 2"
         },
  {
           "customer_id": "10",
           "item_id": " 3"
         }
   }

thanks. 谢谢。

I guess you will be getting the data from the MySQL. 我想您将从MySQL获取数据。

$results = mysqli_query("SELECT customer_id, item_id FROM your_table_name");
$data = array();
while($result = mysqli_fetch_assoc($results)) {
     $data['data'][] = $result;
}

echo json_encode($data);

There are many ways to do this. 有很多方法可以做到这一点。 Here is a suggestion. 这是一个建议。

$data = [
    'Customer' => [
        'customer_id' => 29973,
    ],
    'Item' => [
        ['item_id' => 1 ],
        ['item_id' => 2 ],
        ['item_id' => 3 ]
    ]
];

echo json_encode($data) . "\n";

Output: 输出:

{
    "Customer": {
        "customer_id": 29973
    },
    "Item": [
        {
            "item_id": 1
        },
        {
            "item_id": 2
        },
        {
            "item_id": 3
        }
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM