PHP - 格式化多维数组插入MYSQL? [英] PHP - reformat multidimensional array to insert into MYSQL?
本文介绍了PHP - 格式化多维数组插入MYSQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能解析PHP数组是这样的:
how can I parse php array like this:
$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表是这样的:
to insert into MySQL table like this:
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
键,如 $汽车[悍马] [H2] [长度];
我有点不能让另一个数组尺寸,同时缓存实际的品牌/型号...芹苴,我实际的数组是第一维约3000项(品牌)。
When I use foreach
and like $cars["Hummer"]["H2"]["length"];
I somehow can't get another array dimension and cache the actual brand/model at the same time... Tho, my actual array is about 3000 items in the first dimension (brands).
推荐答案
您需要两个循环,一个是品牌,一个是他们的模型:
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']});";
}
}
这篇关于PHP - 格式化多维数组插入MYSQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文