如何从数组中默认设置多个选择选项

Oud*_*din 1 html php arrays

我正在尝试从数组的 from 中从我的数据库中检索选项/值我想在多选列表中将这些选项/值设置为默认选择,并将它们显示给用户,在那里他们将能够更新他们的必要时提供数据。

//data in database
$mytitle = array(
    'Arbitrator',
    'Attorney',
    'Student',
    'Other'
); 

//data for multiple select
$title = array(
    'Judge' ,
    'Magistrate' ,
    'Attorney' ,
    'Arbitrator',
    'Title Examiner' ,
    'Law Clerk','Paralegal' ,
    'Intern' ,
    'Legal Assistant',
    'Judicial Assistant',
    'Law Librarian' ,
    'Law Educator' ,
    'Attorney',
    'Student',
    'Other'
);

echo "<select name='title[]' multiple='multiple'>";

$test = implode(',', $mytitle);

for ($i=0; $i<=14; $i++) {
    if($test == $title[$i]) {
        echo "<option selected value='$title[$i]'>$title[$i]</option>";
    }
    else {
        echo "<option value='$title[$i]'>$title[$i]</option>";
    }
}

echo "</select>"; 
Run Code Online (Sandbox Code Playgroud)

Rus*_*sak 5

我想你可能有逻辑错误。试试这个作为你的循环:

foreach ($title as $opt) {
    $sel = '';
    if (in_array($opt, $mytitle)) {
        $sel = ' selected="selected" ';
    }
    echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Run Code Online (Sandbox Code Playgroud)