将多维数组的Key和值插入mysql表

时间:2016-06-13 13:20:23

标签: php mysql multidimensional-array

我有一个看起来像这样的数组

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描述的代码非常相似,可以在下面看到

    $metadata = implode(', ', array_shift($publications));
foreach($publications as $publication){
    foreach ($publication as $key => $metadata){
        $key = array_keys($publication);
        //$publication[$key];
        }
 $new_metadata[] = "(" . implode(', ', $publication) . ")";

}   

我如何获得密钥和值?

2 个答案:

答案 0 :(得分: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 . '")';
        }
}   

答案 1 :(得分:0)

1个查询无法执行此操作。 你必须运行数组的循环,并在每一行中运行INSERT mysql。