不同的foreach循环取决于if语句

时间:2017-04-19 11:44:58

标签: php

在PHP中是否可以使用不同的if语句来决定运行哪个foreach循环以避免写出相同的代码。

if($myval == 1)
foreach ($student as $member) // to display just students

elseif($myval == 2)
foreach ($staff as $member)  // to display just staff

elseif($myval == 3)
foreach ($sessional as $member)  // to display just sessional

elseif($myval == 0)
foreach ($allmembers as $member)  // to display all
..then print out either just student, or staff, or sessional records

2 个答案:

答案 0 :(得分:1)

是的,这是可能的。你可以有一个共同的变量,就像你有共同的$member

if($myval == 1)
  $members = $student; // to display just students

elseif($myval == 2)
  $members = $staff;  // to display just staff

elseif($myval == 3)
  $members = $sessional;  // to display just sessional

elseif($myval == 0)
  $members = $allmembers;  // to display all

// ultimately foreach
foreach ($members as $member)  // finally run just once

更好的方法是使用switch个案例......☺

答案 1 :(得分:1)

您可以使用$loopArr变量根据开关案例值存储临时数据。

$loopArr = array();

switch($myval) {
    case 0: $loopArr = $allmembers;
        break;
    case 1: $loopArr = $student;
        break;
    case 2: $loopArr = $staff;
        break;
    case 3: $loopArr = $sessional;
        break;
    default: $loopArr = array();
}

foreach ($loopArr as $member) {
    // Your code here
}