使用PDO从mysql字段中检索json字段


Retrieve a json field from mysql field with PDO

我有一个数据库,其中存储了一些数据,其中一个字段是json字符串。

我在这个字段中插入一个json:

        $stmt->bindParam(":settings", json_encode($widget->settings));

然后,当我尝试检索记录时,我会得到一行,其中settings列为字符串。我需要我的数据是json,所以我应该在输出记录之前解码这个字段。如果我选择:

        $app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));

我得到了这样的东西:

"name":"My Name","label":null,"row":null,"settings":"{'"site'":'"dfsdf'",'"action'":'"UrlInfo'"}"

已转义设置。我应该先解码设置,然后再次编码以输出我的结果。我该怎么办才能解决这个问题?

更新:

我使用PDO检索我的数据,所以我得到了一个数组:

        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

在我保存这个之前,我有:

"settings":{"site":"fff","action":"UrlInfo"}}

检索数据时,应该使用json_decode来反转插入数据时的编码。

foreach ($data as &$row) { // Use reference so we can modify in place
    $row['settings'] = json_decode($row['settings']);
}
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));