2015-05-06 38 views
2

我有一個數據庫表,其中有一列包含json值。我想知道如何使用php mysql查詢從「元素」列中獲取「標題」和「名稱」的值。我如何使用PHP Mysql查詢來獲取mysql表中的json值

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

我會很高興,如果有人能幫助我解決這個問題,謝謝。

+1

您需要從表中獲取記錄和分配通過解碼將它們轉換爲變量。那會像一個數組一樣行事,你可以隨意使用它?獲取數據是正常的,不需要額外的努力。通過查詢只有你不能直接得到它。 –

+1

您無法直接使用查詢提取數據。您需要從列中提取JSON字符串,然後使用'json_decode()'將其解碼。 –

回答

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']; 
0

一旦你從數據庫中獲取記錄$row

$json = json_decode($row['elements']); 
echo $json->book->{0}->title; 

http://ideone.com/9yV33F