在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
答案 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
}