如何通过单个foreach循环操纵两个数组?

时间:2012-11-30 07:30:41

标签: php arrays

我有两个数组。这些数组的值通过表单发布。我想要的是将这些数组的值插入数据库。这是我的代码。

if($_SERVER['REQUEST_METHOD']=='POST') {
    $subject=$_POST['subject'];
    $total=$_POST['total'];
    $attendee_array = $_POST['att'];
    $cnic_array=$_POST['cnic'];

    foreach(($attendee_array as $attendee) and ($cnic_array as $cnic)) {
        $query1=mysql_query("INSERT INTO course VALUES('','$subject','$total','$attendee','$cnic')") or die(mysql_error());
    }
}

它不起作用。我该怎么做这个任务?

3 个答案:

答案 0 :(得分:2)

使用第一个数组的键访问第二个数组中的项目。如果您尝试将参与者0插入cnic 0,参与者1插入cnic 1,则此方法有效。

foreach(($attendee_array as $key => $attendee)) {

    $cnic = mysql_real_escape_string($cnic_array[$key]);
    $attendee = mysql_real_escape_string($attendee);
    // do same as above for all user input ^^^

    $query1=mysql_query("INSERT INTO course VALUES('','$subject','$total','$attendee','$cnic')") or die(mysql_error());

}

我为SQL注入添加了转义,但您应该查看带有参数化查询的现代API,例如PDO或MySQLi。

答案 1 :(得分:0)

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($attendee_array));
$mi->attachIterator(new ArrayIterator($cnic_array));

foreach ( $mi as $value ) {
    list($attendee,$cnic) = $value;
    ....etc
}

答案 2 :(得分:0)

如果您不关心原始数组键,可以使用array_combine将一个数组作为键,将另一个数组作为值,然后在foreach循环中调用键和值:

$name = array('Chris','Steve','Dave');
$city = array('New York','San Diego','Dallas');

foreach(array_combine($name, $city) as $k => $v){
    echo $k.' lives in '.$v.'<br/>';    
}

Chris lives in New York
Steve lives in San Diego
Dave lives in Dallas

所以在你的例子中它看起来像这样:

foreach(array_combine($attendee_array,$cnic_array) as $attendee => $cnic) {
    $query1=mysql_query("INSERT INTO course VALUES('','$subject','$total','$attendee','$cnic')") or die(mysql_error());
}