如何为一个多于1的数组创建一个foreach循环

时间:2013-11-07 22:13:09

标签: php

我需要将4个不同数组的大量数据插入到我的数据库中,但我无法弄清楚如何为此创建foreach循环。

这是我脚本的缩短版本(不介意未完成的查询)。

代码:

$latitudeArray = array(
    array('latitude'=>'52.37124908')
);

$longtitudeArray = array(
    array('longtitude'=>'4.893587136')
);

$bodyArray = array(
    array('body'=>'Waterplastiek: een halfronde vorm met treden waaruit water stroomt naar een in de bestrating uitgeholde granieten goot.')
);

$titleArray = array(
    array('title'=>'ReNESsance-fontein (Nes 45, op plein voor Vlaams Cultureel Centrum, Theater De Brakke Grond)')
);

$mysqli = new MySQLi("localhost", "root", "", "po");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: ({$mysqli->connect_errno}) {$mysqli->connect_error}";
}
// The first part of the SQL query
$query = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`) VALUES (``,``,``,``,``,``)";

// This is the format of a VALUES tuple; it is used
// below in sprintf()
$format = " ('%s', '%s', '%s', '%s', %f, %f),";

// Go over each array item and append it to the SQL query
foreach(array_combine($titleArray,$bodyArray,$latitudeArray) as ) {
    $query .= sprintf(
        $format,
        $mysqli->escape_string($price['PriceDate']),
        $mysqli->escape_string($price['Fund']),
        $mysqli->escape_string($price['Currency']),
        $mysqli->escape_string($price['Class']),
        $mysqli->escape_string($price['NAV']),
        $mysqli->escape_string($price['NavChange'])
    );
}
// The last VALUES tuple has a trailing comma which will cause
// problems, so let us remove it
$query = rtrim($query, ',');

// MySQLi::query returns boolean for INSERT
$result = $mysqli->query($query);

if ($result == false) {
    die("The query did not work: {$mysqli->error}");
} else {
    die("The query was a success!");
}

1 个答案:

答案 0 :(得分:1)

这可能不是您正在寻找的答案,但您应该只使用for循环

$A=array(3,4,2,3,4,4,5,5,6);
$B=array(3,4,2,3,4,4,5,5,6);
$C=array(3,4,2,3,4,4,5,5,6);

for ($i=0;$i<count($A);$i++)
    $query.= $A[$i].' '.$B[$i].' '.$C[$i];

这些方面的东西。 Foreach也可以处理索引,但结果会更加混乱。