PHP - reformat multidimensional array to insert into MYSQL?

后端 未结 4 536
栀梦
栀梦 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 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.

     $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.

提交回复
热议问题