从2维数组中将数据保存到数据库中 - php

时间:2012-01-18 04:23:41

标签: php arrays multidimensional-array

我有2维数组要保存到mysql中。问题是,如何从该数组中获取数据并将其保存到DB中这是我的数组:

Array
(
[1a] => Array
    (
        [ans] => 1
    )

[2a] => Array
    (
        [ans] => 1
        [oth] => ABC
    )

[3a] => Array
    (
        [ans] => 1
    )

[3b] => Array
    (
        [ans] => 2
    )

[3f] => Array
    (
        [oth] => 
    )

因此在保存时,它将如下所示:

| qid | ans | oth |
===================
|  1a |  1  |     |
|  2a |  1  | ABC |
|  3a |  1  |     |
|  3b |  2  |     |
|  3f |     |     |
===================

请帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

假设您拥有名为x

的数组
foreach($x as $key=>$details)
{
   $qid = $key;
   $ans = $details["ans"];
   $oth = $details["oth"];
   //Then Save to DB
   // Insert into table (qid,ans,oth) values('$qid',$ans,'$oth') ...

}

答案 1 :(得分:0)

foreach ($your_array as $qid => $value) {
   $ans = isset($value['ans']) ? $value['ans'] : null;
   $oth = isset($value['oth']) ? $value['oth'] : null;
   //then you get the $qid, $ans, $oth and insert them to the db.
   ....
}