【问题标题】:How to insert json array into mysql database with multiple records as like db image如何将json数组插入具有多条记录的mysql数据库中,如db image
【发布时间】:2017-04-15 07:17:25
【问题描述】:

我有这个 json 数组,它将作为给定图像插入到 mysql 表中:

[{"F_relation":"Son","F_name":"fhj","F_address_type":"Other","F_address":"55556","F_phone":"556"}, {"F_relation":"Husband","F_name":"fhj","F_address_type":"Other","F_address":"5566","F_phone":"889"}, {"F_relation":"Husband","F_name":"fhj","F_address_type":"Same","F_address":"ak, USA, 5566","F_phone":"89888789"}]

【问题讨论】:

  • 那么您面临的问题是什么?
  • 首先将json转换为数组,然后在数据库中插入数组值
  • 解析并插入。如果您使用的是 MySQL 5.7,您可以将原始数据保存在 JSON 列中。
  • 我只想插入它!如果它可能有多个数组,它们都只用逗号分隔!
  • 你试过什么?显示您的代码,并指出您遇到问题的地方。

标签: php mysql arrays json


【解决方案1】:

使用json_decode 将json字符串转换为数组。

$json='[{"F_relation":"Son","F_name":"fhj","F_address_type":"Other","F_address":"55556","F_phone":"556"},{"F_relation":"Husband","F_name":"fhj","F_address_type":"Other","F_address":"5566","F_phone":"889"},{"F_relation":"Husband","F_name":"fhj","F_address_type":"Same","F_address":"ak, USA, 5566","F_phone":"89888789"}]';
//store the  json string in a variable 

$a=json_decode($json,true); //will convert json string to array
$len=sizeof($a);
for($i=0;$i<$len;$i++){
    $F_relation=$a[$i]['F_relation']; //retrieve values 
    $F_name=$a[$i]['F_name'];
    $F_address_type=$a[$i]['F_address_type'];
    $F_address=$a[$i]['F_address'];
    $F_phone=$a[$i]['F_phone'];

    //write your query to insert, perform other operation 
}

【讨论】:

    【解决方案2】:
    var res = jQuery.parseJSON(response.responseText);
    var result = res.d;
    

    因此您可以将其用作数组,例如:result[0].F_relation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多