循环多维数组并对每对值子数组执行 INSERT 查询

问题描述 投票:0回答:3

我正在寻找一种实用的方法,为每 2 个内容数组记录创建一个新的数据库记录,并使用前一个子数组的日期值。至于你的问题:内容总是有 24 条记录(0-23),如果划分的话应该是 12 块。

[
    [
        'date' => '2018-05-23',
        'content' => [
            [
                'AAAAAA',
                'BBBBBB',
                'CCCCCC',
                'DDDDDD',
                'EEEEEE',
                'FFFFFF',
                'GGGGGG',
                'HHHHHH',
                'IIIIII',
                'JJJJJJ',
                //...
            ],
        ],
    ],
    [
        'date' => '2018-05-22',
        'content' => [
            [
                'KKKKKK',
                'LLLLLL',
                'MMMMMM',
                'NNNNNN',
                //...
            ],
        ],
    ],
];

我需要能够创建一个

foreach
循环,该循环将从 3 个变量创建数据库记录。

foreach
#1:

$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // AAAAAA
$content = $array['content'][0][$key]; // BBBBBB

foreach
#2:

$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // CCCCCC
$content = $array['content'][0][$key]; // DDDDDD

直到完成第一个子数组,然后转到第二个数组:

foreach
#6:

$date = $array['content']['date']; //2018-05-22
$headline = $array['content'][0][$key]; // KKKKKK
$content = $array['content'][0][$key]; // LLLLLL

我一直在尝试使用

array_chunk
对数组进行分组,但没有成功,然后我尝试编写一个小修复程序来正确排序数组:

if ($x <= 10) {
        if ( $a < 2 ) {
            $a++;
        } else {
            $x++;
            $a = 1;
        }
    $res[$i]['content'][$x][] = ltrim($text);
} else {
    $res[$i]['content'][$x][] = ltrim($text);
    $x = 0;
}

结果:

[date] => 2018-05-23
            [content] => Array
                (
                    [0] => Array
                        (
                            [0] => AAAAAA
                            [1] => BBBBBB
                        )

                    [1] => Array
                        (
                            [0] => CCCCCC
                            [1] => DDDDDD
                        )

                    [2] => Array
                        (
                            [0] => EEEEEE
                            [1] => FFFFFF
                        )

                    [3] => Array
                        (
                            [0] => GGGGGG
                            [1] => HHHHHH
                        )

这对第一个数组有效,但所有其他数组都失去了顺序并且没有正确分类。

有什么想法如何创建它吗?

php arrays mysqli prepared-statement sql-insert
3个回答
1
投票

我不确定你的数据库结构是什么样的,因为你没有提到,但你可以这样做:

<?php
$array = [
    [
        "date" => "date",
        "content" => [["A", "B", "C"]]
    ],
    [
        "date" => "date",
        "content" => [["E", "F", "G", "H"]]
    ],
];

$sql = "INSERT INTO table (content, date) VALUES ";

foreach ($array as $key => $item) {
    $content = $item["content"][0];
    for ($i = 0; $i < count($content); $i += 2) {
        $letters = $content[$i];

        if (isset($content[$i + 1])) {
            $letters .= $content[$i + 1];
        }

        $sql .= "('$letters', '$item[date]'),";
    }
}

$sql = rtrim($sql, ",") . ";";

echo $sql;

将输出:

INSERT INTO table (content, date) VALUES ('AB', 'date'),('C', 'date'),('EF', 'date'),('GH', 'date');

1
投票
<?php

$collection = 
        array
            (
                array
                    (
                        'date' => '2018-05-23',
                        'content' => array
                            (
                                array
                                    (
                                        'AAAAAA',
                                        'BBBBBB',
                                        'CCCCCC',
                                        'DDDDDD',
                                        'EEEEEE',
                                        'FFFFFF',
                                        'GGGGGG',
                                        'HHHHHH',
                                        'IIIIII',
                                        'JJJJJJ'
                                    )
                            )
                    ),
                array
                    (
                        'date' => '2018-05-22',
                        'content' => array
                            (
                                array
                                    (
                                        'KKKKKK',
                                        'LLLLLL',
                                        'MMMMMM',
                                        'NNNNNN'
                                    )
                             )
                    )
            );


function getChunks($data){
    $result = array();
    $length = count($data);

    for($i=0;$i<$length;$i += 2){
        $result[] = array($data[$i],$data[$i+1]);
    }

    return $result;
}

function groupContentByDate($collection){
    $result = array();

    foreach($collection as $each_data){
        $result[$each_data['date']] = array('content' => array());
        foreach($each_data['content'] as $each_content){
            $result[$each_data['date']]['content'] = array_merge($result[$each_data['date']]['content'],getChunks($each_content));
        }
    }

    return $result;
}


echo "<pre>";
print_r(groupContentByDate($collection));

输出

Array
(
    [2018-05-23] => Array
        (
            [content] => Array
                (
                    [0] => Array
                        (
                            [0] => AAAAAA
                            [1] => BBBBBB
                        )

                    [1] => Array
                        (
                            [0] => CCCCCC
                            [1] => DDDDDD
                        )

                    [2] => Array
                        (
                            [0] => EEEEEE
                            [1] => FFFFFF
                        )

                    [3] => Array
                        (
                            [0] => GGGGGG
                            [1] => HHHHHH
                        )

                    [4] => Array
                        (
                            [0] => IIIIII
                            [1] => JJJJJJ
                        )

                )

        )

    [2018-05-22] => Array
        (
            [content] => Array
                (
                    [0] => Array
                        (
                            [0] => KKKKKK
                            [1] => LLLLLL
                        )

                    [1] => Array
                        (
                            [0] => MMMMMM
                            [1] => NNNNNN
                        )

                )

        )

)

0
投票

最优雅的是,使用父循环

foreach()
来访问日期和条目子数组。通过从
foreach()
返回的数据喂养子
array_chunk()
循环条目对。

  • 从 PHP8.2 开始,您可以使用
    execute_query()
    在单个操作中创建、绑定和执行准备好的语句。
  • 从 PHP8.1 开始,您可以将值数组传递给
    execute()
  • 在 PHP8.1 之前,在进入循环之前将变量绑定到准备好的语句上,然后确保绑定的变量已由循环赋值,然后在子循环内执行该语句。

这将为每个日期和内容值对在数据库中稳定、安全地插入一个新行。

PHP8.2代码:(PHPize演示)

$sql = "INSERT INTO your_table (date, content1, content2) VALUES (?,?,?)";
foreach ($array as ['date' => $date, 'content' => [0 => $entries]]) {
    foreach (array_chunk($entries, 2) as $pair) {
        $mysqli->execute_query($sql, [$date, ...$pair]);
    }
}

PHP8.1代码:(PHPize演示)

$stmt = $mysqli->prepare("INSERT INTO your_table (date, content1, content2) VALUES (?,?,?)");
foreach ($array as ['date' => $date, 'content' => [0 => $entries]]) {
    foreach (array_chunk($entries, 2) as $pair) {
        $stmt->execute([$date, ...$pair]);
    }
}

PHPize 演示)

$stmt = $mysqli->prepare("INSERT INTO your_table (date, content1, content2) VALUES (?,?,?)");
$stmt->bind_param("sss", $date, $content1, $content2);
foreach ($array as ['date' => $date, 'content' => [0 => $entries]]) {
    foreach (array_chunk($entries, 2) as [$content1, $content2]) {
        $stmt->execute();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.