2016-06-13 50 views
0

我有一個數組,看起來像這樣插入多維數組到MySQL表的key和值

Array 
(
    [0] => Array 
     (
      [post_id] => 5410 
      [Issue] => 201 
      [volume] => 2 
      [pages] => 105-9 
      [authors] => Onger, M., Jaluth, K. 
      [publication_date] => 17 January 2016 
      [journals] => Nature Medicine 
      [link_to_pubmed] => http://www.ncbi.nlm.nih.gov/pubmed/1 
     ) 
    [1] => Array 
     (
      [post_id] => 5411 
      [Issue] => 301 
      [volume] => 7 
      [pages] => 32-9 
      [authors] => Onger, M., Jaluth, K. 
      [publication_date] => March 30 
      [journals] => Lancet 
      [link_to_pubmed] => http://www.ncbi.nlm.nih.gov/pubmed/2 
     ) 
     ) 

我已經開裂我的頭整天試圖找出如何我可以同時插入鍵和值得到的東西看起來像這樣

+---------+---------+-------------------+-----------------------+ 
| meta_id | post_id | meta_key   | meta_value   | 
+---------+---------+-------------------+-----------------------+ 
| 190143 | 5410 |Issue    | 201     | 
| 190141 | 5410 |volume    | 2      | 
| 190140 | 5410 |pages    | 105-109    | 
| 190139 | 5410 |authors   | Onger, M., Jaluth, K. | 
| 190144 | 5410 |publication_date | 17 January 2016  | 
| 190136 | 5410 |journals   | Nature Medicine  | 
| 190135 | 5410 |link_to_pubmed  |      | 
|   |   |     |      | 
+---------+---------+-------------------+-----------------------+ 

我已經使用的代碼是作爲一個描述here並且可以在下面

可以看出十分相似10

我如何獲得關鍵和值?

+2

你嘗試過什麼碼? – splash58

+1

幾個帶有INSERT嵌套的'foreach'es,simplez。你堅持什麼特定的部分? –

+0

@ splash58我編輯過的帖子/問題快照代碼 – tapeli

回答

1

如果meta_id是一個自動增量字段,然後

foreach($publications as $publication) { 
    // Get post_id and remive it from array 
    $post_id = $publication['post_id']; 
    unset($publication['post_id']); 
    foreach ($publication as $key => $metadata) { 
     // Below a query. I only print it, you need to execute it 
     echo $query = 'insert into table (post_id, meta_key, meta_value) 
         values ($post_id, "' . $key . '", "' . $metadata . '")'; 
     } 
} 
+0

這應該適合你。 – mishka

+0

@ splash58輝煌的東西。多數民衆贊成我正在尋找。我從來沒有想過一個解決方案,以同樣的方式,你想.....謝謝! – tapeli

0

你不能用1個查詢來完成。 你必須運行數組的循環,並在每一行運行INSERT mysql。