使用MSSQL和PHP在数据库中同时保存数组键和值


Save Array Key and Value at the same time in Database with MSSQL and PHP

我想保存一个数组的键和值在一个数据库的foreach循环与mssql和php。

这是我的数组,我编码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"
}

try use this -

<?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();
?>

试试这个

<?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);
?>