【问题标题】:PHP - reformat multidimensional array to insert into MYSQL?PHP - 重新格式化多维数组以插入 MYSQL?
【发布时间】:2011-03-22 16:26:39
【问题描述】:

我怎样才能像这样解析 php 数组:

$cars= array(
    "Ford"=>array("C-Max"=>array("length"=>"4333","width"=>"1825","height"=>"1560"),"Escape"=>array("length"=>"4480","width"=>"1845","height"=>"1730")
    ,"Explorer"=>array("length"=>"4912","width"=>"1872","height"=>"1849"),"Fiesta"=>array("length"=>"3950","width"=>"1973","height"=>"1433")
    ,"Focus"=>array("length"=>"4488","width"=>"1840","height"=>"1497"),"Fusion"=>array("length"=>"4013","width"=>"1724","height"=>"1543")
    ,"Galaxy"=>array("length"=>"4820","width"=>"1854","height"=>"1723"),"Kuga"=>array("length"=>"4443","width"=>"1842","height"=>"1677")
    ,"Mondeo"=>array("length"=>"4844","width"=>"1886","height"=>"1500"),"Ranger"=>array("length"=>"5075","width"=>"1805","height"=>"1745")
    ,"S-Max"=>array("length"=>"4768","width"=>"1854","height"=>"1658"),
    "Hummer"=>array("H2"=>array("length"=>"5170","width"=>"2063","height"=>"2012"),"H3"=>array("length"=>"4782","width"=>"1989","height"=>"1872")));

像这样插入 MySQL 表:

CREATE TABLE IF NOT EXISTS `cars_dimensions` (
  `id` int(10) NOT NULL auto_increment,
  `brand` varchar(120) character set utf8 NOT NULL,
  `model` varchar(120) character set utf8 NOT NULL,
  `length` varchar(5) character set utf8 NOT NULL,
  `width` varchar(5) character set utf8 NOT NULL,
  `height` varchar(5) character set utf8 NOT NULL,
  KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

当我使用foreach$cars["Hummer"]["H2"]["length"]; 时,我不知何故无法获得另一个数组维度并同时缓存实际的品牌/型号......不过,我的实际数组在第一个维度中大约有 3000 个项目(品牌)。

【问题讨论】:

  • 到目前为止,每个答案都假定悍马与福特处于同一水平,但在您的示例中并非如此,也许这只是一个错字。如果是他们的代码将起作用,如果不是,到目前为止的 3 个答案都不合适。
  • 是的,抱歉,我只是以错误的方式复制粘贴了代码 :)

标签: php mysql arrays multidimensional-array


【解决方案1】:

您需要两个循环,一个用于品牌,一个用于他们的模型:

foreach ($cars as $brand => $models) {
    foreach ($models as $model => $specs) {
        $query = "INSERT INTO cars_demensions (brand, model, length, weight, height)
                  VALUES ('$brand', '$model', {$specs['length']}, {$specs['width']}, {$specs['height']});";
    }
}

【讨论】:

    【解决方案2】:
    foreach ( $cars as $brandname => $carinfo  )
    {
    foreach ( $carinfo  as $modelname => $car )
    {
    // brand = $brandname
    // model = $modelname
    // length = $car['length']
    // do insert query here
    }
    }
    

    【讨论】:

      【解决方案3】:
      
      $rows = '';
      foreach($cars AS $brand) {
        foreach($brand AS $model) {
          if(!empty($rows)) $rows .= ', ';
          $rows = "({$car['width']},...)";
        }
      }
      
      $sql = "INSERT INTO cars_dimensions (width,...) VALUES $rows";
      

      【讨论】:

        【解决方案4】:

        完整的可执行代码和测试。这是执行此操作的更有效和更快的方法。使用这种方式,您可以使用单个插入查询插入多行。

        <?php 
        $col = [];
        foreach ($cars as $brand => $models) {
            foreach ($models as $model => $specs) {
                if (isset($specs['length']) || isset($specs['width']) || isset($specs['height'])) {
                    $length = $specs['length'];
                    $width = $specs['width'];
                    $height = $specs['height'];
                } else {
                    foreach ($specs as $k => $v) {
                        $length = $v['length'];
                        $width = $v['width'];
                        $height = $v['height'];
                    }
                }
                $col[] = "('" . $brand . "', '" . $model . "', '" . $length . "', '" . $width . "', '" . $height . "')";
            }
        }
        $query = "INSERT INTO `cars_dimensions`(`brand`, `model`, `length`, `width`, `height`) VALUES" . implode(',', $col) . ";";
        
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "test";
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $conn->exec($query);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
        ?>
        

        希望对您有所帮助。谢谢。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-12
          • 2017-07-03
          • 1970-01-01
          • 1970-01-01
          • 2011-12-06
          • 2017-12-17
          • 2021-12-18
          • 2014-05-28
          相关资源
          最近更新 更多