如何在 foreach 循环中将多维数组组合在一起?

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

我正在尝试构建一个用于向数据库中插入的 SQL 语句,但不幸的是,由于语句的构造方式,语句的值侧与语句的列侧不对齐.

这是当前数据:

Incoming data: Array ( [0] => Array ( [ID] => 1 [Status] => High ) [1] => Array ( [ID] => 2 [Status] => High ) )

After the foreach: Array ( [0] => 1 [1] => High [2] => 2 [3] => High )

Constructed query: INSERT IGNORE INTO regions (ID, Status) VALUES ('1'), ('High'), ('2'), ('High');

这是我要找的结果:

Construct query: INSERT IGNORE INTO regions (ID, Status) VALUES ('1', 'High'), ('2', 'High');

这是当前正在创建当前查询的函数:

    function insert($table, &$data) {
        require("getConnection.php");

        $query = "INSERT IGNORE INTO $table ";
        $query .= "(";

        foreach($data as $key => $value) {
            if(is_array($value)) {
                foreach($value as $innerkey => $innervalue) {
                    $columns = implode(", ", array_keys($value));
                }
            } else {
                $columns = $key;
            }
        }

        // Get count of columns
        $columnCount = count(explode(", ", $columns));

        $query .= $columns . ") VALUES ('";

        foreach($data as $key => $value) {
            if(is_array($value)) {
                foreach($value as $innerkey => $innervalue) {
                    $values[] = $innervalue;
                }
            } else {
                $values[] = $key;
            }
        }

        $query .= implode("'), ('", $values) . "');";

        $result = mysqli_query($conn, $query) or die(mysqli_error($conn));
        
        // Finished with insert()
        mysqli_close($conn);

        return $result;
    }

一些附加信息是传入数据是动态的,它可能有更多或更少的密钥/对。

php mysql arrays multidimensional-array foreach
© www.soinside.com 2019 - 2024. All rights reserved.