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

Backslash in json_encode (PHP) + JSON_ARRAYAGG (mySQL)

问题是数组颜色中带有引号的反斜杠。我认为这是因为 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"
  }
]

您正在编码 colors 两次。首先在 SQL 中,然后在 PHP 中。您可以做的是在 PHP 中解码 colors,然后在 中编码 $data:

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