解析php数组以生成insert语句

时间:2017-07-27 20:06:55

标签: php mysql

嗨我有这样的数组:

$datas = 
[
    'name_1'=>'John',
    'name_2' =>'Mickey',
    'settings_1' => 'Settings 1',
    'settings_2' => 'Settings 2'
]

foreach($datas as $data){
    //get items here...
}

如何配对或解析这些项​​以生成如下的插入语句:

INSERT INTO table (name, settings)VALUES('John','Settings 1');
INSERT INTO table (name, settings)VALUES('Mickey','Settings 2');

有什么想法吗?提前谢谢。

3 个答案:

答案 0 :(得分:1)

$datas = 
[
    'name_1'=>'John',
    'name_2' =>'Mickey',
    'settings_1' => 'Settings 1',
    'settings_2' => 'Settings 2'
];

$results = [];

foreach($datas as $index=>$data){

  //create an array out of $index breaking it at the '_' 
  //so array will be $parts = [0=>'name', 1=>'1'];
  $parts = explode('_', $index);
  //'name_1'=>'John' = $results[1]['name'] = 'John';
  $results[$parts[1]][$parts[0]] = $data;


}
//batch insert new formed array
//INSERT INTO tbl_name (name, settings) VALUES $results;

答案 1 :(得分:1)

此代码可用于创建数组数组。考虑数组键将是name_x和settings_x

foreach($datas as $key=>$value){
    // explode each key of the array
    $keys = explode('_',$key);
    $name = 'name_'.$keys[1];
    $settings = 'settings_'.$keys[1];
    // to generate array
    $new_array[$keys[1]]=array('name'=>$datas[$name], 'settings'=>$datas[$settings]);

}
print_r($new_array);

循环$ new_array以进行插入查询。

输出:

Array
(
    [1] => Array
        (
            [name] => John
            [settings] => Settings 1
        )

    [2] => Array
        (
            [name] => Mickey
            [settings] => Settings 2
        )

)

答案 2 :(得分:1)

检查一下,你必须做一些中间步骤。关于代码的评论!!

        $datas = 
        [
            'name_1'=>'John',
            'name_2' =>'Mickey',
            'settings_1' => 'Settings 1',
            'settings_2' => 'Settings 2'
        ];

        $data_final = [];    


        foreach($datas as $key=>$value){
              $keyX =  preg_replace('/^(.+)_(\d+)$/', '$1', $key);// get the "type" (name, setting)
              $keyY =  preg_replace('/^(.+)_(\d+)$/', '$2', $key);// get the "index" (_1, _2  without "_")

              $data_final[$keyY][$keyX] = $value; // put in result
        }

        // make queries
        $sql = [];
        foreach($data_final as $datas){

                $fields = implode(", ", array_keys($datas)); //implode the keys to sql fields
                $values = implode(", ", array_map(function($a){return "'$a'";}, array_values($datas)));//implode values to sql values adding ''. WARNING: This not escape values. Use escape string function on mysqli obj or PDO to the right escape
                $sql[] = "INSERT INTO table ($fields) VALUES ($values);"; // populate query

        }
        $sql = implode("\n", $sql); // implode with new line
        print_r($sql); //results

重要提示:

  • 您必须拥有正确的语法" field_number"尊重程序
  • 您甚至可以使用每个记录中的两个字段中的一个或多个
  • 您可以使用任何字段名称,始终尊重" field_number"语法

<强> DEMO HERE