PHP - reformat multidimensional array to insert into MYSQL?

后端 未结 4 530
栀梦
栀梦 2020-12-17 07:06

how can I parse php array like this:

$cars= array(
    \"Ford\"=>array(\"C-Max\"=>array(\"length\"=>\"4333\",\"width\"=>\"1825\",\"height\"=>\         


        
相关标签:
4条回答
  • 2020-12-17 07:44

    You need two loops, one for the brands and one for their models:

    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']});";
        }
    }
    
    0 讨论(0)
  • 2020-12-17 07:49
    
    $rows = '';
    foreach($cars AS $brand) {
      foreach($brand AS $model) {
        if(!empty($rows)) $rows .= ', ';
        $rows = "({$car['width']},...)";
      }
    }
    
    $sql = "INSERT INTO cars_dimensions (width,...) VALUES $rows";
    
    0 讨论(0)
  • 2020-12-17 07:55
    foreach ( $cars as $brandname => $carinfo  )
    {
    foreach ( $carinfo  as $modelname => $car )
    {
    // brand = $brandname
    // model = $modelname
    // length = $car['length']
    // do insert query here
    }
    }
    
    0 讨论(0)
  • 2020-12-17 08:02

    Full executable code and TESTED. This is more efficient and faster way to do this. Using this way you can insert multiple row using a single insert query.

    <?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();
    }
    ?>
    

    Hopefully it should help you. Thank you.

    0 讨论(0)
提交回复
热议问题