2017-04-05 5 views
1

Hallo Ich habe Array wie diesePHP-Array vermeiden Offset undefiniert

$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 

Und das drucken ich

tat
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>"; 

} 

Als Student "Matt" ist hat 11 nicht subject_id Es wird mir geben ein Fehler Hinweis

Hinweis: Undefiniert offset: 11

Wie ignorieren ich es und Druck N/A, wenn der Student nicht das Thema jede Hilfe für Ihre

Sie haben danken und Anregungen

+4

vor dem Druckcheck 'if (isset ($ array [$ offset]))' –

+1

Mein schlechtes, So lustig Wie ignoriere ich das DANK – sanu

Antwort

1

Sie isset() zusammen mit count() verwenden: -

if(isset($subjects[$subject_id]) && count($subjects[$subject_id])>0){ 
    foreach ($subjects[$subject_id] as $mark){ 
     echo "$mark\t"; 
    } 
} 

können Sie verwenden !empty() mit count() Check zu: -

if(!empty($subjects[$subject_id]) && count($subjects[$subject_id])>0){ 
    foreach ($subjects[$subject_id] as $mark){ 
     echo "$mark\t"; 
    } 
} 
+0

Simple Isset Arbeitete für mich danke – sanu

+0

@sanu 'count()' hinzugefügt, so dass, wenn Array hat keinen Wert, dann stoppt der Iterationsteil. Wenn das Array leer ist, wird auch der Iterationsteil (mindestens einmal) im Fall von 'isset()' fortgesetzt. –

+0

Ja Danke Ihre Antwort ist klarer Also werde ich diese Antwort annehmen – sanu