how can I parse php array like this:
$cars= array(
\"Ford\"=>array(\"C-Max\"=>array(\"length\"=>\"4333\",\"width\"=>\"1825\",\"height\"=>\
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']});";
}
}
$rows = '';
foreach($cars AS $brand) {
foreach($brand AS $model) {
if(!empty($rows)) $rows .= ', ';
$rows = "({$car['width']},...)";
}
}
$sql = "INSERT INTO cars_dimensions (width,...) VALUES $rows";
foreach ( $cars as $brandname => $carinfo )
{
foreach ( $carinfo as $modelname => $car )
{
// brand = $brandname
// model = $modelname
// length = $car['length']
// do insert query here
}
}
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.