我有一个 MySQL 数据库,其中一列包含原始 JSON 数据(这来 self 无法控制的 joomla 组件)。
我需要检索此 JSON 数据并使用 PHP 对其进行操作。我用来检索数据的代码如下(我稍后会整理它,仅用于演示目的);
$query = "SELECT text FROM `myTable` WHERE catid = 92";
$result = $conn->query($query);
while ($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
print("<pre>".print_r($row,true)."</pre>");
// $array = json_encode($row);
// echo $array;
}
print_r($row,true)
的输出是 this .
在上面的注释代码中 echo $array
生成 https://pastebin.com/YUUMR2ZG
如您所见,该数组包含一个名为 [text]
的键。这包含所有 JSON 数据。
如何访问此 JSON 数据,特别是 title
部分 ("title":"Waterside Parish"
)
基本上,我需要访问数组的 title
和 text
部分,以便可以在 html 表格中显示它们。
也许我没有正确编码/解码结果?
如有任何建议,我们将不胜感激。
最佳答案
使用 json_decode("你的数据", true);它将数据转换为数组。在我看来,它比 stdClass 好得多,后者成为 json_decode("your data") 的结果
通用示例:
$object = json_decode('{"a":"b"}', true);
echo $object['a'];
你的例子:
$query = "SELECT text FROM `myTable` WHERE catid = 92";
$result = $conn->query($query);
$data = $result->fetchAll(PDO::FETCH_ASSOC);
var_dump(json_decode($data[0]['text'],true));
关于php - 从 MySQL DB 列中选择 JSON 数据并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57221557/