如何在foreach中使用多个数组?

时间:2014-12-01 09:13:30

标签: php mysql arrays

  1. 如何在foreach中使用多个数组?

    更正此语法

     $URRightsFor =   $_POST['URRightsFor'];
     $URRightsName =   $_POST['URRightsName'];
     foreach ($URRightsName,$URRightsFor as $key => $value) {
        $sql= "INSERT INTO tblUserRights (`URUserId`,`URRightsName`,`URRightsFor` )value( '$URUserId','$URRightsName[$key]','$URRightsFor[$key]')";
        $result=mysql_query($sql);
     }
     if($result) {
       echo "Thank you!";
     } 
     else {
      ECHO'ERROR';
     }
    

1 个答案:

答案 0 :(得分:0)

您可以使用SPL的MultipleIterator

$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($_POST['URRightsFor']), 'rightsFor');
$mi->attachIterator(new ArrayIterator($_POST['URRightsName'], 'rightsName'));
foreach($mi as $details) {
    echo $details['rightsFor'], ' - ', $details['rightsName'], PHP_EOL;
}

或者如果您使用的是更新版本的PHP,则可以在list

中使用foreach
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($_POST['URRightsFor']));
$mi->attachIterator(new ArrayIterator($_POST['URRightsName']));
foreach($mi as list($rightsFor, $rightsName)) {
    echo $rightsFor, ' - ', $rightsName, PHP_EOL;
}

或者您可以使用以下方法将两个数组合并为一个

$rightsArray = array_combine(
    $_POST['URRightsFor'],
    $_POST['URRightsName']
);
foreach($rightsArray as $rightsFor => $rightsName) {
    echo $rightsFor, ' - ', $rightsName, PHP_EOL;
}