0

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

$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

4 回答 4

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>';
    }
  }
}

希望这可以帮助!

于 2012-05-10T20:26:30.517 回答
1

第一的。正如@itsmeee 所说,您又错过了一个遍历该县城市数组的 foreach。除此之外,您的输入数组缺少 2 个关闭括号来包装每个状态的数据数组。

如果你解决这个问题,我会这样做:

$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);

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

祝你好运!

于 2012-05-10T20:26:40.240 回答
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) . "')";
于 2012-05-10T20:11:56.757 回答
0

好像你又错过了一个 foreach:

foreach($county as $name => $cities) {
 foreach ($cities as $city) {
....
于 2012-05-10T20:20:11.003 回答