【问题标题】:How to insert in php fo array of string value? [closed]如何在php中插入字符串值数组? [关闭]
【发布时间】:2019-12-30 17:29:51
【问题描述】:

我有一个数组

   Array(  
         [0] => Column 1, Column 2 ,Column 3,Column 4,Column 5,Column 6
         [1] => 19506,7254,321878,8,1,60 
         [2] => 187486,685,377,3,0,0 
         [3] => 187498,682285,3354,45,1,400 
         [4] => 18498,681285,38959,2,0,0 
      )

使用循环或任何其他解决方案存储到 mysql 表中 怎么插入数据库 我在表中有完全相同的列

【问题讨论】:

  • 能否请您添加更多关于您的连接方法以及您迄今为止尝试过的信息。
  • 这个数组是怎么来的?处理数据的方式似乎很奇怪。

标签: php mysql arrays string


【解决方案1】:

使用下面的sn-p将其转换成数组保存到数据库中,

// replace spaces with "" and explode with comma
$keys = explode(",", str_replace(" ","",$arr[0]));
array_shift($arr); // remove first index
$arr = array_map(function($a) use($keys){
    // first value as keys and rest array values exploding and combining as key value pair
    return array_combine($keys, explode(",",$a));
}, $arr);

Demo

创建插入查询的代码

$sql = "INSERT INTO table_name (".implode(",",$keys).") VALUES ";
foreach($arr as $data){
    $sql .= "(".implode(",",$data)."),";
}
$sql = rtrim($sql,",");
echo $sql;

输出

INSERT INTO table_name (Column1,Column2,Column3,Column4,Column5,Column6)  
VALUES (19506,7254,321878,8,1,60),(187486,685,377,3,0,0), 
(187498,682285,3354,45,1,400),(18498,681285,38959,2,0,0)

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2021-10-27
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多