在循环中将多数组插入数据库

时间:2016-10-06 11:53:29

标签: php mysql arrays multidimensional-array insert

我有以下数组

Array
(
  [user_id] => Array
    (
        [0] => 1
        [1] => 1
        [2] => 1
        [3] => 1
    )

  [menu_id] => Array
    (
        [0] => 1
        [1] => 1
        [2] => 1
        [3] => 1
    )

 [submenu_id] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
    )

  )

我的MySQL数据库如下所示:

user_id | menu_id | submenu_id
        |         |  

我想将上面的数组插入到我的数据库中,如下所示:

user_id | menu_id | submenu_id
    1   |   1     |  1
    1   |   1     |  2
    1   |   1     |  3
    1   |   1     |  4

我如何插入上面的数据?谢谢。

1 个答案:

答案 0 :(得分:0)

因为你在每个数组上都有相同的索引,你希望从第一个数组(user_id)获得第一个值,从第一个数组获得第一个值(menu_id),依此类推,并将其添加到一行中MySQL的。

你需要这样的东西:

foreach($data['user_id'] as $key => $user_id){
    //You have $user_id
    $menu_id = $data['menu_id'][$key];
    $submenu_id = $data['submenu_id'][$key];
    //All of this 3 variables you need now to insert to mysql. Try it and let me know WITH code if something is not working like this.
}