如何使用php在数据库中插入动态数组值

时间:2017-02-03 09:21:12

标签: php

动态数组下方:

array (size=11)
  'reward_title' => 
    array (size=2)
      0 => string 'kishan' (length=6)
      1 => string 'kishan' (length=6)
  'amount' => 
    array (size=2)
      0 => string '100' (length=3)
      1 => string '200' (length=3)
  'description' => 
    array (size=2)
      0 => string 'k' (length=1)
      1 => string 'kk' (length=2)
  'estimated_delivery' => 
    array (size=2)
      0 => string '02/02/2017' (length=10)
      1 => string '02/03/2017' (length=10)

数据库表下方屏幕截图:

screenshot

我的问题:如何将动态数组插入我的数据库表。请帮助我............................... ............................................

1 个答案:

答案 0 :(得分:0)

您可以像这样生成查询:

//Helpers
$columns = array();
$values = array();
$parameters = array();
$itemCount = -1;

//Iterate array
foreach($yourArray as $key => $value) {
    //Parse columns and parameters
    $columns[]=$key;
    $parameters[]=":".$key;
    $values[$key] = $value;
    //We need the number of records to be inserted later
    if ($itemCount === -1) {
        $itemCount = count($value);
    }
}

//This is how the query will look like with the help of $columns and $parameters
$sql = "insert into yourtable(".implode(",", $columns).") values(".implode(",", $parameters).")";
//Iterate record indexes
for($index = 0; $index < $itemCount; $index++) {
    //We assume your PDO object is called $dbh and prepare the statement
    $stmt = $dbh->prepare($sql);
    //Iterate $column/$parameter indexes
    for($innerIndex = 0; $innerIndex < count($columns); $innerIndex++) {
        //and bind the parameters
        $stmt->bindParam($parameters[$innerIndex], $values[$columns[$innerIndex]][$index]);
    }
    //Execute the statement
    $stmt->execute();
}

代码未经测试,请阅读更多here