如何使用循环将此数组[$ obj]插入mysql?
Array
(
[apple] => Array
(
[0] => fruit
[1] => 15
)
[cat] => Array
(
[0] => animal
[1] => 400
)
[pumpkin] => Array
(
[0] => vegetables
[1] => 20
)
[orange] => Array
(
[0] => fruit
[1] => 30
)
)
我想使用这样的循环将数组[$ obj]插入到mysql中。
|___id__|___ product__|_____type_____|__price__|
| 1 | apple | fruit | 15 |
| 2 | cat | animal | 400 |
| 3 | pumpkin | vegetables | 20 |
| 4 | orange | fruit | 30 |
我该怎么做?
谢谢。
答案 0 :(得分:4)
$sql = "INSERT INTO tableName (product, type, price) VALUES";
foreach($array as $key => $value)
{
$sql += " ('$key', '$value[0]', $value[1]),";
}
$sql += substr_replace($sql,"",-1). ";";
//perform your INSERT here.
请务必将tableName
和$array
替换为各自的名称
答案 1 :(得分:0)
尝试这个$ obj是你的数组
$finalarray = array();
foreach($obj as $main_key=>$main_value)
{
$product = $main_key;
$type = $main_value[0];
$price = $main_value[1];
$string = "('','$product','$type','$price')";
$finalarray[] = $string;
}
$final_values_array = implode(',',$finalarray);
mysql_query("INSERT INTO TABLENAME('id','product','type','price') VALUES $final_values_array");
答案 2 :(得分:0)
试试这个
$array=Array
(
[apple] => Array
(
[0] => fruit
[1] => 15
)
[cat] => Array
(
[0] => animal
[1] => 400
)
[pumpkin] => Array
(
[0] => vegetables
[1] => 20
)
[orange] => Array
(
[0] => fruit
[1] => 30
)
)
$query = "INSERT INTO tableName (product, type, price) VALUES";
$sub='';
foreach($array as $key => $value)
{
$sub.="('$key', '$value[0]', $value[1]), ";
}
$sql = $query . substr_replace($sub,"",-1);
这是批量插入