将多维数组信息插入数据库

时间:2012-05-10 20:08:13

标签: php mysql sql

这似乎有一个非常简单的解决方案......但我很难搞清楚。我需要一个数组进入数据库。例如:

$usa = array(
'idaho' => array(
           county1 => array(
                     'pocatello', 'arimo', 'downey'
                      ),
           county2 => array(
                      'bear', 'cuprum', 'mesa'
                      )
'iowa' => array(
           county1 => array(
                     'des moines', 'adel', 'desoto'
                      ),
           county2 => array(
                      'douglas', 'grant', 'jasper'
                      )

);

我尝试了这种插入数据库的方法:

foreach($usa as $state => $county){
    foreach($county as $name => $city){
    $s=$state;
    $county_name = strtolower($name);
    $city = strtolower($city);
    $us = "INSERT INTO us
           SET state='{$s}',county='{$county_name}',city='{$city}'
           ";
    $us_result = mysql_query($us,$connection);
         }
  }

我认为问题是foreach(将状态变量传递给第二个foreach循环)。我尝试了很多不同的方法。在此先感谢您的帮助!

***注意:当我删除插入的$ s = $ state变量和state ='{$ s}'部分时,一切都很好。我仍然无法插入状态

4 个答案:

答案 0 :(得分:1)

有两个主要问题。

首先,您的数组没有正确分隔,最好对县名使用单引号或双引号,无论如何您要将其称为字符串:

$usa = array(
  'idaho' => array(
       'county1'=>array(
                 'pocatello', 'arimo', 'downey'
                  ),
       'county2'=>array(
                  'bear', 'cuprum', 'mesa'
                  )),
  'iowa' => array(
       'county1'=>array(
                 'des moines', 'adel', 'desoto'
                  ),
       'county2'=>array(
                  'douglas', 'grant', 'jasper'
                  ))

);

其次,还应该有一个foreach循环来计算城市名称:

foreach($usa as $state => $county){
  foreach($county as $name => $city){
    foreach ($city as $cityname) {
      $s = $state;
      $county_name = strtolower($name);
      $city = strtolower($cityname);
      $us = "INSERT INTO us SET state='{$s}',county='{$county_name}',city='{$city}'";
      echo $us.'<br>';
    }
  }
}

希望这有帮助!

答案 1 :(得分:1)

首先。正如@itsmeee所说的那样,你错过了另一个遍布该县城市阵列的foreach。除此之外,您的输入数组缺少2个紧密的parens来包装每个状态的数据数组。

如果你解决了我的问题:

$us     = "INSERT INTO us (state, county, city) VALUES ";
$values = array();

foreach($usa as $state => $county){
    foreach($county as $name => $cities){
        foreach($cities as $city){
            $county_name = strtolower($name);
            $city        = strtolower($city);
            $values[]    = "('{$state}','{$county_name}','{$city}')";
        }
    }
}

$us       .= join(',',$values);
$us_result = mysql_query($us,$connection);

这将构建插入字符串并一次完成所有插入。您也可以进行单独的插入,但对于数据集来说,这样做一个大的插入更有效。

祝你好运!

答案 2 :(得分:0)

您的INSERT查询不正确。 试试这个:

$us = "INSERT INTO us (state, county, city) VALUES ('" . mysql_real_escape_string ($s) . "', '" . mysql_real_escape_string ($county_name) . "', '" . mysql_real_escape_string ($city) . "')";

答案 3 :(得分:0)

好像你错过了另一个foreach:

foreach($county as $name => $cities) {
 foreach ($cities as $city) {
....