如何使用PHP Mysql查询在mysql表中获取json值

时间:2015-05-06 20:41:21

标签: php mysql json

我有一个数据库表,其中一列包含一个json值。我想知道我如何使用php mysql查询获取" title"的值。和"名称"来自"元素"列。

id | name | elements
---------------------
 1 | Dan  | { 
                "book": { 
                "0": { "title": "The Oblivion of Hope"  }           
                },
                "author": {
                 "0": { "name": "David Addoteye" },
                 "1": { "date": "2015-93-13"}
                 }
            }

elements => book => 0 => title

elements => author=> 0 => name

如果有人可以帮我解决这个问题,我会很高兴的,谢谢你。

2 个答案:

答案 0 :(得分:1)

从数据库中获取条目并使用json_decode()将其转换为关联数组。

http://repl.it/msZ

一些示例代码:

// Equivalent of obtained from DB query.
$fetched_value = '{"book":{"0":{"title":"The Oblivion of Hope"}},"author":{"0":{"name":"David Addoteye"},"1":{"date":"2015-93-13"}}}';

$decoded = json_decode($fetched_value, true);

echo $decoded['book'][0]['title'];
echo $decoded['author'][0]['name'];

答案 1 :(得分:0)

从数据库中获取记录DISTINCT后:

$row

http://ideone.com/9yV33F