我希望使用mssql和php将数组的键和值保存在数据库的foreach循环中。
这是我的数组,我在json($ myArr)上编码:
{
"UPC-A": "55055",
"EAN-13": "7077707",
"UPC": "0940",
"GTIN": "009642",
"GTIN-14": "566642"
}
这是我的代码:
foreach($myArr as $key => $val){
$insert = "Insert Into tbl (barcodeType,barcode) Values ($key, $val)"
$stmtBar = $db->prepare($insertBarcode);
$stmtBar->execute();
//what is the best approach for this???
}
当从数据库json编码时,输出应该是这样的:
{
"barcodeType": "UPC-A",
"barcode": "55055"
},
{
"barcodeType": "EAN-13",
"barcode": "7077707"
}
答案 0 :(得分:0)
试试这个
<?php
$jsonData = '{
"UPC-A": "55055",
"EAN-13": "7077707",
"UPC": "0940",
"GTIN": "009642",
"GTIN-14": "566642"
}';
$myArr = json_decode($jsonData);
foreach($myArr as $key => $val){
$insert = "Insert Into tbl (barcodeType,barcode) Values ($key, $val)"
$stmtBar = $db->prepare($insertBarcode);
$stmtBar->execute();
}
$selectStmt = "select * from tbl";
$jsonArray = array();
foreach ($db->query($selectStmt) as $results)
{
$jsonArray[] = array('barcodeType' => $results['barcodeType'],'barcode' => $results['barcode']);
}
$result = json_encode($jsonArray,true);
var_dump($result);
?>
答案 1 :(得分:0)
尝试使用此 -
<?php
$a = '{
"UPC-A": "55055",
"EAN-13": "7077707",
"UPC": "0940",
"GTIN": "009642",
"GTIN-14": "566642"
}';
$myArr = json_decode($a);
$values = '';
foreach($myArr as $key => $val){
$values .= "(".$key.",".$val."),";
}
$insert = "Insert Into tbl (barcodeType,barcode) Values ".rtrim($values,',');
$stmtBar = $db->prepare($insert);
$stmtBar->execute();
?>