PHP 数组向后输出

标签 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);

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

最佳答案

好吧,你在另一个数组中有一个数组,所以......

$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相反,并使用 PDO ,或MySQLi -this article将帮助您决定哪个。如果您选择 PDO,here is a good tutorial .

关于PHP 数组向后输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221704/

相关文章:

php - 如何使用数据库和 PHP session 来存储用户的购物车?

PHP多选表单在MySQL中插入多行

php - 我可以将完整的 MySQL 数据库从基于 PHP 的站点移动到 Django 应用程序吗?

mysql - SQL查询以正确的顺序显示2列

java - 创建通用堆栈数组

c# - 使用 linq 和 lambdas 的多分隔字符串到对象列表

PHP echo 返回确认函数斜杠

mysql - 加入一对多 - 显示每个外键的多个表的第一行

javascript - REST API - Node、Express、MySQL - 如何通过 URL 传递有限数量的对象来过滤 JSON(来自数据库)返回

android - 有时解析在数组中包含数组的 JSON