Codded
Codded

Reputation: 1256

php array for each in for each

I am trying to get a select list with values from $staff The bit i am struggling is selecting the staff that are already enrolled from $entry->enrolments.

If the $staff id exists in $entry->enrolments select it in the select list

$entry = Record from mysql

$staff = list of staff in an array.

$entry->enrolments = comma seperated values of enrolled staff

<select name="tutor[]" id="tutor" multiple="multiple" size="5" class="required" title="Select Staff">

<?php
    $entry = get_record("staff_development", "id", $id);
    $staff = get_records("user", "deleted", "0", "lastname ASC", "id,firstname,lastname,idnumber");
    $sdenrolments=array($entry->enrolments);
    $people = explode(",", $entry->enrolments);


    foreach($staff as $tutor){
    foreach($people as $person){

    if($tutor->id>1)echo '<option value="'.$tutor->id.'"';
    if ($person==$tutor->id) {echo 'selected="selected"';}
    echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
    }
    }
?>

</select>

Any help/guidance would be greatly appreciated. Thanks in advance

Upvotes: 0

Views: 127

Answers (2)

Aaron W.
Aaron W.

Reputation: 9299

Your if block is confusing. You are checking for $tutor->id > 1 when opening the option tag, but aren't when closing it. PaulP.R.O mentions in_array which you should replace your foreach loops with. Here is your if block cleaned up and set the check for selection inline.

if($tutor->id > 1) {
    echo '<option value="'.$tutor->id.'" ' . (($person==$tutor->id) ? ' selected="selected"': '') . '>';
    echo $tutor->lastname.' '.$tutor->firstname;
    echo '</option>';
}

Upvotes: 1

Paul
Paul

Reputation: 141827

in_array is the easiest way to tell if a value is in an array :) Replace your loops with this:

foreach($staff as $tutor){
    echo '<option value="'.$tutor->id.'"';
    if(in_array($tutor->id, $people))
        echo 'selected="selected"';
    echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}

You might also want to rename your variable from people to enrolled_staff or something a bit more clear.

Upvotes: 3

Related Questions