0

I need to insert a mass load of data from 4 different arrays into my database, but I can't figure out how to make a foreach loop for this.

This is a shortened vesion of my script (don't mind the unfinished query).

code:

$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!");
}
4

1 回答 1

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 也可以处理索引,但结果会更加混乱。

于 2013-11-07T22:21:55.513 回答