将 JSON 数组转换为 php 中的插入查询字符串

Convert JSON array into an insert query string in php

我有一个 JSON 数组,我需要将它转换成插入查询字符串, 有人知道怎么做吗?

这是 JSON 字符串

$array = '[
   {
     "table":"customer",
     "data":
       [
         {
           "name":"Johny",
           "address":"jl. abc no 5",
           "where" :

             {
               "customerid":1
             }

         },
         {
           "name":"Doko",
           "address":"jl. kerinci 7"
           "where" :

             {
               "customerid":2
             }
         }
       ]
   },
   {
     "table":"supplier",
     "data":
       [
         {
           "id":123
         },
         {
           "id":234
         }
       ]
   }
]
';

然后我用json_decode把它转换成数组

$obj = json_decode($array,true);

这是我目前所做的解决方法。

foreach($obj as $result){
  $table = $result['table'] . "</br>";
  $data =  $result['data'];
  $string = "INSERT INTO $table (";
  foreach($data as $subdata ){
    foreach($subdata as $key=>$val){
      $string .= "$key,";
      $string .= ")VALUES (";
      $string .= "'$val'" . ",";
    }
    $string .= ");";
  }
  echo $string."</br>";
}

但它并没有像我想要的那样工作,

我需要的是将其转换成类似

的查询
INSERT INTO customer(customerid,address)values('1','jl.abc no 5');
INSERT INTO customer(customerid,address)values('2','jl. kerinci no 7');
INSERT INTO supplier(id)values('123');
INSERT INTO supplier(id)values('234');

提前致谢。

PS:数组可以是两个以上的数组,也可以是一个。

=========================================== ==============================

更新:读取数组然后将其拆分为更新查询字符串 喜欢

UPDATE customer SET name="JOHNY", address="jl. abc no 5";
UPDATE customer SET name="Doko", address="jl. kerinci 7";

当 "where" 键存在时,当 "where" 键不存在时忽略它

我没有执行 foreach,而是首先使用 for 语句首先迭代数组,因为您的 json 具有索引和键值对的组合。这是:

    $query = "";
    for($i = 0, $ctr = count($obj); $i < $ctr; $i++) {
        for($x = 0, $ctr_data = count($obj[$i]["data"]); $x < $ctr_data; $x++) {
            $query2 = array(); // After loop cleans the array
            $query .= "INSERT INTO "  . $obj[$i]["table"];
            $query .= "(";
                foreach($obj[$i]["data"][$x] as $key => $value) {
                    $query2[] = $key;
                }
                $query .= implode(",", $query2) . ") VALUES";  // glue the commas

                $query2 = array(); // After the first foreach cleans the array

                foreach($obj[$i]["data"][$x] as $key => $value) {
                    $query2[] = "'$value'";
                }
                $query .= "(";
                $query .= implode(",", $query2) . ") <br>"; // glue the commas
        }
    }

    echo $query;

编辑:

  1. 第一个循环首先计算数组的数量,在你的例子中是两个。
  2. 第二个循环计算键"data"上的数组。
  3. 准备一个数组 $query2 = array();这样您就可以在键 "data".
  4. 上获得 key/values 值的容器
  5. 获取索引 "table" 名称。
  6. 第三个循环用于密钥 "data" 获取其密钥。
  7. 将密钥存储在 $query2 上供以后使用。
  8. 使用内爆功能,所有按键用逗号粘在一起。
  9. 再次准备数组 $query2 以清理数组。
  10. 第四个循环用于键 "data" 获取其值。
  11. 重复数字 6。
  12. 重复数字 7。

第 1 步:创建 class Database.php 到下面的 excel 查询代码

<?php 
/*
  * Author: luongitvnsoft@gmail.com
    * Language: Vietnamme
    * Site url: http://itvnsoft.com
    * Youtube: Itvnsoft Web Developer
    * Phone:   0986 421 127
    * File Database.php 
    * khai báo các thông tin kết nối database
    * ccs hằng số HOST DB_NAME DB_USER DB_PASS khai bóa bên file config.php
  */
try {
 $db = new PDO('mysql:host='.HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $db->exec("set names utf8");

 function getAll($table,$limit = 10){
    global $db;
    $sql = "SELECT * FROM $table LIMIT $limit";
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    return $stmt->fetchAll();
 }


function insert($table,$data){
    global $db;
    if(isset($data) && is_array($data)){
        $files = array_keys($data);
        $files = implode($files, ',');
        $values = array_values($data);
        $values = implode($values, "','");

        $sql = "Insert Into $table($files) values('$values')";
        // $conn->exec($sql)
        $db->exec($sql);
        return $db->lastInsertId();
    }else{
        return false;
    }

}



  } catch (PDOException $e) {
    die( "Error!: " . $e->getMessage());
  }

?>

第 2 步:在您的 php 页面处理 php json 代码中

include 'Database.php';

foreach($obj as $result){
  $table = $result['table'] . "</br>";
  $data =  $result['data'];
  insert($table,$data);
}