0

因为这个答案,我要问。

我的代码看起来像

<?php
$lines = file('file.txt');
$count = count($lines);
$i = 0;
$query = "INSERT INTO table VALUES ";
foreach($lines as $line){
    $i++;
    if ($count == $i) {
        $query .= "('".$line."')";
    }
    else{
        $query .= "('".$line."'),";
    }
}
echo $query;

有没有更优雅的方式在 php 中执行此/功能?

4

4 回答 4

4
foreach ( $lines AS $line )  
{  
  $query[] = "($line)";  
}  

echo  "INSERT INTO table VALUES " . implode(",",$query);

是如何使用内爆来做到这一点,但我认为 AlienWebguy 的更好

于 2011-07-23T23:59:57.000 回答
3
$query = 'INSERT INTO table VALUES ';
$query .= "('" . implode("'), ('", $lines) . "')";

更新

对于 2 个字段,它可能看起来像(我想你使用 php5+):

$query = 'INSERT INTO table VALUES ';

$lines = array(array(1,2), array(3,4));
$query .= "('" . implode("'), ('", array_map(function($i) { return "'" . implode("', '", $i) . "'"; }, $lines)) . "')";

var_dump($query);
于 2011-07-23T23:48:37.290 回答
3
foreach(file('file.txt') as $line){
    $query .= "('".$line."'),";
}
echo "INSERT INTO table VALUES " . rtrim($query,',');
于 2011-07-23T23:49:54.017 回答
1

LOAD DATA INFILE 更适合此特定任务:http ://dev.mysql.com/doc/refman/5.1/en/load-data.html

于 2011-07-23T23:56:11.100 回答