这是我要解析的数组,并将各个值插入数据库。
Array
(
[0] => Array
(
[custInfo] => Ujwal 9975022560
[rate] => 24000
[weight] => 21.00000
[desc] => GENTS ANGTHI 22k NO STONE
[makingAmt] => 200
[sum_total] => RS.156283.38
[vat] => RS.3064.38
[itemTotal] => 51073
[barcode] => BQSP78BB
[net_rate] => 24200
[date] => 2015-12-02
[invoiceNo] => 2
[bill_type] => Invoice
)
[1] => Array
(
[custInfo] => Ujwal 9975022560
[rate] => 24000
[weight] => 21.00000
[desc] => GENTS ANGTHI 22k NO STONE
[makingAmt] => 200
[sum_total] => RS.156283.38
[vat] => RS.3064.38
[itemTotal] => 51073
[barcode] => BQSP78BB
[net_rate] => 24200
[date] => 2015-12-02
[invoiceNo] => 2
[bill_type] => Invoice
)
[2] => Array
(
[custInfo] => Ujwal 9975022560
[rate] => 24000
[weight] => 21.00000
[desc] => GENTS ANGTHI 22k NO STONE
[makingAmt] => 200
[sum_total] => RS.156283.38
[vat] => RS.3064.38
[itemTotal] => 51073
[barcode] => BQSP78BB
[net_rate] => 24200
[date] => 2015-12-02
[invoiceNo] => 2
[bill_type] => Invoice
)
)
我怎样才能使用这个多维数组并使用php插入到mysql表中。我想做一个这样的插入:
$sql = "INSERT INTO selected_items
(custInfo, invoiceNo, barcode, desc,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES
('$custInfo','$invoiceNo','$barcode','$desc',
'$weight','$rate','$makingAmt','$net_rate',
'$itemTotal','$vat','$sum_total','$bill_type','$date')";
$res = mysqli_query($sql,$con);
<?php
require "init.php";
if($_POST){
$arrAssoc = json_decode(stripslashes($_POST['jsonarray']), true);
$fields = array_map(function($v){
return implode("','",$v);
},$arrAssoc);
$query="INSERT INTO selected_items
(custInfo, invoiceNo, barcode, description,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES ('".implode("'),('",$fields)."')";
if(mysqli_query($con,$query))
{
echo "Data inserted";
}else{
echo "Data insertion error".mysqli_error($con);
}
}
else{
print_r("Nothing came from android code"+"Data insertion error".mysqli_error($con));
}
?>
答案 0 :(得分:-2)
尝试使用array_map
和implode
功能,如
$fields = array_keys($your_array[0]);
$values = array_map(function($v){
return implode("','",$v);
},$your_array);
$query="INSERT INTO selected_items
(".implode(',',$fields).")
VALUES ('".implode("'),('",$values)."')";