如何打破foreach循环-数组索引

时间:2018-08-31 06:11:17

标签: php arrays

我的动态数组,形成为

$exam = explode(',',$row['exam']);

例如结果是:

$exam = array("First-Term","Second-Term", "Third-Term");

我们可以这样获取索引和值

foreach (array_values($exam) as $i => $value) {
  echo "$i: $valuen";
  echo "//And its mark";
}

但是,如何中断每个索引的循环。我必须按以下步骤获取

First-Term
//And its mark

Second-Term
// And its mark

Third-Term
// And its mark

但是在使用foreach循环时,我得到了

First-Term
Second-Term
Third-Term
//And its mark
//And its mark
//And its mark

如何中断每个索引的循环,此后,我们在每个索引中使用相同的代码。我只是尝试为每个术语分配每个标记

$exam[0]{
    //here is $value
    //rest of the code, same code to every index
}

$exam[1]{
    //here is $value
    //rest of the code, same code to every index
}

$exam[2]{
    //here is $value
    //rest of the code, same code to every index
}

$exam[...]{
    //
}

3 个答案:

答案 0 :(得分:1)

从您所做的工作来看,您正在使用两个具有不同输出的foreach循环...

这个:

$exam = array("First-Term","Second-Term", "Third-Term");

foreach (array_values($exam) as $i => $value) {
    echo "{$value}<br>";
    echo "// And its mark<br><br>";
}

将输出以下内容:

First-Term
//And its mark

Second-Term
// And its mark

Third-Term
// And its mark

此循环中:

$exam = array("First-Term","Second-Term", "Third-Term");

foreach (array_values($exam) as $i => $value) {
    echo "{$value}<br>";
}
foreach (array_values($exam) as $i => $value) {
    echo "// And its mark<br>";
}

将输出以下内容:

First-Term
Second-Term
Third-Term
// And its mark
// And its mark
// And its mark

一旦我有更多详细信息,将更新此答案。 经过测试的代码:https://3v4l.org/RDvYN

答案 1 :(得分:0)

您应该为teammarks创建两个数组,然后像这样在同一foreach循环中解析这两个数组

$team = array('a', 'b', 'c', 'd' );
$marks = array('1', '2', '3', '4' );

foreach(array_combine($team, $marks) as $t => $m) {
    echo $t . "<br>" .$m . "<br><br>"; //$t for team and m for marks
    echo "<br/>";
}

通过这种方式,您可以以并行方式解析不同的数据

答案 2 :(得分:-1)

我将构建一个数组,将所有内容放置在适当的位置,然后开始显示它:

$exam = array("First-Term","Second-Term", "Third-Term");
$marks = array(1, 2, 3);

$result = array();
foreach (array_values($exam) as $idx => $value) {
    $result[] = array(
         "exam" => $value,
         "mark" => $marks[$idx]
    );
}

foreach ($result as $value) {
    echo $value['exam'] . "\n";
    echo $value['mark'] . "\n\n";
}