PHP 数组避免未定义的偏移量
PHP array avoid Undefined offset
你好,我有这样的数组
$subject_names[7]="English";
$subject_names[11]="Software Engeneering";
//Student can choose multiple subjects and each subject have int_mark and ext_mark
$results['Matt'][7]['int_mark'] =15;
$results['Matt'][7]['ext_mark'] =55;
$results['Josh'][7]['int_mark'] =12;
$results['Josh'][7]['ext_mark'] =45;
$results['Josh'][11]['int_mark'] =14;
$results['Josh'][11]['ext_mark'] = 52;
// the array is to maintain crosstab format
为了打印这个我做了
echo "Student Name\t";
foreach($subject_names as $subject_name)
{
echo "$subject_name\t";
}
echo "<br>";
foreach ($results as $student_name => $subjects)
{
echo "$student_name\t";
foreach($subject_names as $subject_id => $sub_name){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}
echo "<br>";
}
因为学生 "Matt" 没有 subject_id 11 它给我一个错误通知
Notice: Undefined offset: 11
如果学生没有那个主题,我如何忽略它并打印 N/A
感谢您的帮助和建议
您可以将 isset()
与 count()
一起使用:-
if(isset($subjects[$subject_id]) && count($subjects[$subject_id])>0){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}
您也可以使用 !empty()
和 count()
检查:-
if(!empty($subjects[$subject_id]) && count($subjects[$subject_id])>0){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}
你好,我有这样的数组
$subject_names[7]="English";
$subject_names[11]="Software Engeneering";
//Student can choose multiple subjects and each subject have int_mark and ext_mark
$results['Matt'][7]['int_mark'] =15;
$results['Matt'][7]['ext_mark'] =55;
$results['Josh'][7]['int_mark'] =12;
$results['Josh'][7]['ext_mark'] =45;
$results['Josh'][11]['int_mark'] =14;
$results['Josh'][11]['ext_mark'] = 52;
// the array is to maintain crosstab format
为了打印这个我做了
echo "Student Name\t";
foreach($subject_names as $subject_name)
{
echo "$subject_name\t";
}
echo "<br>";
foreach ($results as $student_name => $subjects)
{
echo "$student_name\t";
foreach($subject_names as $subject_id => $sub_name){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}
echo "<br>";
}
因为学生 "Matt" 没有 subject_id 11 它给我一个错误通知
Notice: Undefined offset: 11
如果学生没有那个主题,我如何忽略它并打印 N/A
感谢您的帮助和建议
您可以将 isset()
与 count()
一起使用:-
if(isset($subjects[$subject_id]) && count($subjects[$subject_id])>0){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}
您也可以使用 !empty()
和 count()
检查:-
if(!empty($subjects[$subject_id]) && count($subjects[$subject_id])>0){
foreach ($subjects[$subject_id] as $mark){
echo "$mark\t";
}
}