如何提取下面的数组&插入3个数据& 2查询
提取此阵列&给我2排& 3栏
Array
(
[name] => Array
(
[0] => AAAAA
[1] => BBBBB
)
[number] => Array
(
[0] => 7878787878
[1] => 9898989898
)
[email] => Array
(
[0] => a@gmail.com
[1] => b@gmail.com
)
)
我们需要通过foreach循环进行以下查询
INSERT INTO `contact_person` SET customer_id='131',cp_name='AAAAA',cp_phone='7878787878',cp_email='a@gmail.com
INSERT INTO `contact_person` SET customer_id='131',cp_name='BBBBB',cp_phone='9898989898',cp_email='b@gmail.com'
答案 0 :(得分:3)
考虑像for loop一样:
$length = count($yourarray['name']);
$queries = new array();
for(i = 0; i < $length; i++) {
$queries[] = "INSERT INTO `contact_person` SET customer_id='131',
cp_name='" . $yourarray['name'][i] . "',
cp_phone='" . $yourarray['number'][i] . "',
cp_email='" . $yourarray['email'][i] " . "'";
}
这将创建所有插入查询并将它们放在名为$queries
注意:此代码假设您总是拥有相同数量的姓名,号码和电子邮件
答案 1 :(得分:1)
$newArr = array();
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$newArr[$k][$key] = $v;
}
}
echo "<pre>"; print_r($newArr);
现在,您可以在foreach()
中运行插入查询,例如:
foreach($newArr as $key=>$val){
echo "INSERT INTO `contact_person` SET customer_id='131',
cp_name='" . $val['name'] . "',
cp_phone='" . $val['number'] . "',
cp_email='" . $val['email'] " . "'";
echo "<br />";
}
答案 2 :(得分:1)
您可以使用以下函数汇总数组。
function getSummary($array){
$summary = [];
foreach( $array as $col => $data ){
foreach( $data as $key => $value ){
$summary[$key][$col] = $value;
}
}
return $summary;
}
一旦将汇总数组传递给下面的函数,您将获得查询。我假设您需要INSERT
查询。
function makeQueries($summary){
foreach( $summary as $data ) {
echo $sql = "INSERT INTO `contact_person` (customer_id, cp_name, cp_phone, cp_email) VALUES (131, '{$data['name']}', '{$data['number']}', '{$data['email']}');";
echo "<br>";
}
}
我相信这两个功能将解决您的问题
答案 3 :(得分:1)
使数据库中的customer_id成为自动编号,以便在插入时自动生成customer_id。
此外,所有字段都是db
中的一些文本字段$arr = Array
(
'name' => Array
(
"AAAAA", "BBBBB"
),
'number' => Array
(
"7878787878", "9898989898"
),
'email' => Array
(
"a@gmail.com", "b@gmail.com"
)
);
$count = count($arr['name']);
$sql = "";
if ($count > 0) {
$sql = "INSERT INTO `contact_person` (cp_name, cp_phone, cp_email) VALUES ";
for ($i=0; $i < $count; $i++) {
$sql .= ($i+1==$count) ? "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."'')" : "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."''), ";
}
}
echo ($sql);