gpt4 book ai didi

php - json_encode (PHP) + JSON_ARRAYAGG (mySQL) 中的反斜杠

转载 作者:行者123 更新时间:2023-11-29 15:28:41 24 4
gpt4 key购买 nike

问题是数组颜色中带有引号的反斜杠。我认为这是因为 JSON_ARRAYAGG 但我不知道如何打印正确的 json。

查询:

SELECT a.id_product, JSON_ARRAYAGG(c.name_color) as colors, a.url 
FROM products as a
LEFT JOIN product_has_colors b ON a.id_product = b.id_product
LEFT JOIN colors c ON c.id_color = b.id_color
GROUP BY a.id_product;

+------------+-------------------+-----------------+
| id_product | colors | url |
|------------+-------------------+-----------------+
| 1 | ["yellow", "blue"]| https://url.com |
| 2 | ["black, "green"] | https://url.com |
+------------+-------------------+-----------------+

PHP:

header('Content-Type: application/json);
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

输出:

[
{
"id_product: "1",
"colors": [\"yellow\", \"blue\"]",
"url": "https://url.com"
},
{
"id_product: "2",
"colors": [\"black\", \"green\"]",
"url": "https://url.com"
}
]

最佳答案

您正在对颜色进行两次编码。首先使用 SQL,然后使用 PHP。您可以做的是在编码 $data 之前在 PHP 中解码 colors:

foreach ($data as $key = $row) {
$data[$key]['colors'] = json_decode($row['colors']);
}

如果您作为对象获取,则使用:

foreach ($data as $obj) {
$obj->colors = json_decode($obj->colors);
}

或者完全用 SQL 生成 JSON:

SELECT JSON_ARRAYAGG(JSON_OBJECT(
'id_product', id_product,
'colors', colors,
'url', url
)) as json
FROM (
SELECT a.id_product, JSON_ARRAYAGG(c.name_color) as colors, a.url
FROM products as a
LEFT JOIN product_has_colors b ON a.id_product = b.id_product
LEFT JOIN colors c ON c.id_color = b.id_color
GROUP BY a.id_product
) x

关于php - json_encode (PHP) + JSON_ARRAYAGG (mySQL) 中的反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com