我试图从 MySQL 数据库中的两个表中获取一个 JSON 对象,但没有任何返回。
product table: id, title, description, price
product_colors table: id, product_id, product_color
我的 PHP 代码:
$st = $conn->prepare ('SELECT `product`.id , `product`.title, `product`.description, `product`.price, GROUP_CONCAT(`product_colors`.product_color) AS colors FROM `product` LEFT JOIN `product_colors` ON `product`.id = `product_colors`.product_id GROUP BY `product`.id');
$st->execute();
$products = [];
$rows = $st->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$row['product_colors'] = explode(',', $row['product_color']);
$products[] = $row;
}
echo json_encode ($products);
这是我想要得到的:
[
{
id: 4,
title: 'Car',
description: "Pellentesque orci lectus",
price: '120$',
product_color: ['Red', 'Blue', 'Black']
},
{
id: 6,
title: 'Bus',
description: "orci lectus",
price: '10$',
product_color: ['White', 'Blue', 'Green']
}
]
最佳答案
所以最后我得到了答案,首先查询是正确和完美的,获取和循环中的错误,所以这是完美的解决方案并且更容易:
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$r['colors']=explode(',', $r['colors']); //colors like what i named the GROUP_CONCAT
$rows[] = $r;
关于php - 使用 PDO 从两个表中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58514765/