PHP Array倒退了

时间:2013-06-20 19:02:27

标签: php mysql arrays

这是我当前输出的preg_match_all

Array
(
[0] => Array
    (
        [0] => 2 Sentence text here
    )

)

Array
(
[0] => Array
    (
        [0] => 3 Sentence text here.
        [1] => 4 Sentence text here.
        [2] => 5 Sentence text here.
    )

)

我正在尝试将每个输出作为表中的新行插入,但它认为每个[0] [1] [2]都是一个新列。如何将数组插入mysql?

$query = "INSERT INTO table (col1) VALUES ";
foreach ($matches as $item) {
$query .= "('".$item[0]."'),";
}
$query = rtrim($query,",");
$result = mysql_query($query);

以上显然只插入数组的第一行

1 个答案:

答案 0 :(得分:1)

嗯,你在其他数组中有一个数组,所以......

$query = "INSERT INTO table (col1) VALUES ";

if(!empty($matches))
{
    foreach ($matches as $item) {
        foreach ($item[0] as $items) {
            $query .= "('".$items."'),";
        }
    }
}

if(!empty($matches))
{
    foreach ($matches[0] as $item) {
        $query .= "('".$item."'),";
    }
}

取决于你如何获得阵列匹配。


$query = rtrim($query,",");
$result = mysql_query($query);

这样你就会得到这个问题:

INSERT INTO table (col1) VALUES ('2 Sentence text here'), ('3 Sentence text here'), ('4 Sentence text here'), ('5 Sentence text here')

使用单个INSERT语句在一个列中插入多个值的有效方法。

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial