更新查询中使用的嵌套foreach循环中的数据

时间:2016-03-27 12:56:54

标签: php mysql arrays foreach nested-loops

这是我的代码:

session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */

// studevent_result = 
foreach ($_SESSION['arrayNameResult'] as $value) {
    $studResult = $_GET[$value];
    echo $studResult;
    echo "<br>";
}

// result_postion = 
foreach ($_SESSION['arrayNamePosition'] as $value) {
    $studPosition = $_GET[$value];
    echo $studPosition;
    echo "<br>";
}

echo "<br>";

// stud_id = 
foreach ($_SESSION['arrayId'] as $value) {
    echo $value;
    echo "<br>";
}

// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
    UPDATE result
    SET studevent_result = '00:20:33',
        result_position = '6'
    WHERE result.stud_id = '12'
";

$updateRow = mysqli_query($conn, $updateQuery);

我使用$ _SESSION变量,它们都存储一个数组。我使用foreach循环提取这些数组的结果。

在$ updateQuery中,我想将studevent_result =设为上面第一个foreach循环的结果,result_position =上面第二个foreach循环的结果,result.stud_id =上面第三个foreach循环的结果。

在我编辑代码后,我的代码现在看起来像这样:

foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
        foreach ($_SESSION['arrayNamePosition'] as $data) {
            $studPosition = $_GET[$data];
    foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
    UPDATE result
    SET studevent_result = '$studResult',
        result_position = '$studPosition'
    WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
            }
        }
    }

我嵌套了foreach循环。但现在的问题是,对于嵌套循环中的最后一个foreach循环,查询中的$ idValue仅使用数组$ _SESSION ['arrayId']中的最后一个元素。如何解决此问题以循环整个数组,以便查询使用数组中的所有值?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,这应该可以帮到你

session_start();
$i = 0;
$studResult = array(); 
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value]; 
$i++;
}

$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}


$stud_id = array(); $i=0; 
 foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}

for($j =0; $j<$i; $j++){
  $updateQuery = "
  UPDATE result
  SET studevent_result = '$studResult[$j]',
    result_position = '$studPosition[$j]'
  WHERE result.stud_id = '$stud_id[$j]'
  ";

  $updateRow = mysqli_query($conn, $updateQuery);
}

希望它会有所帮助。快乐编码:)