【问题标题】:Save Array Key and Value at the same time in Database with MSSQL and PHP使用 MSSQL 和 PHP 在数据库中同时保存数组键和值
【发布时间】:2016-09-16 08:31:07
【问题描述】:

我想用 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"
}

【问题讨论】:

    标签: php arrays sql-server


    【解决方案1】:

    试试这个 -

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

    【讨论】:

      【解决方案2】:

      试试这个

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

      【讨论】:

      • 我需要先从第一个json编码格式插入到数据库中
      • 我也添加了插入
      猜你喜欢
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2012-06-29
      • 2014-09-22
      • 2018-08-01
      相关资源
      最近更新 更多