[英]Replacement for JSON_ARRAYAGG and JSON_OBJECT from MySQL in v5.6 or PHP
[英]Backslash in json_encode (PHP) + JSON_ARRAYAGG (mySQL)
问题是数组 colors 中带引号的反斜杠。 我认为这是因为 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);
OUTPUT:
[
{
"id_product: "1",
"colors": [\"yellow\", \"blue\"]",
"url": "https://url.com"
},
{
"id_product: "2",
"colors": [\"black\", \"green\"]",
"url": "https://url.com"
}
]
您正在编码colors
两次。 首先是 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
我在 MYSQL 和 PHP 上使用 JSON_ARRAYAGG 我正在使用这个函数来删除反斜杠:
function isJson($string) {
json_decode($string, true);
return (json_last_error() == JSON_ERROR_NONE);
}
function result_as_json($result, $array_columns = null){
$json = array();
foreach($result as $res) {
$item = array();
if($array_columns != null){
foreach ( $array_columns as $key) {
$item[$key] = isJson($res[$key])?json_decode($res[$key], true):$res[$key];
}
}
else {
foreach ($res as $key => $value) {
$item[$key] = isJson($value)?json_decode($value, true):$value;
}
}
array_push($json, $item);
}
return json_encode($json);
}
我希望它有帮助:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.