简体   繁体   中英

populate select input with array

I would like to start out saying I don't want to use Javascript....

I have an array which is returning correctly I believe, however I am only having the first entry in the array display in the drop down list.

Is this a problem with the array? or with this function?

foreach($array as $key=>$value){
    $html = "<option value='$key'>$value</key>";
}

echo "<select name="process">$html</select>";

You have to use the concatenation operator ( . ):

$html = '';
foreach($array as $key => $value)
{
    $html.= "<option value='$key'>$value</option>";
}

echo "<select name=\"process\">$html</select>";

However, looking at the function you posted earlier, mysql_fetch_assoc only returns a single row at a time. You need to loop over that, instead. The following should suffice:

function tasks_list($p_id) { 
    $project_tasks = array(); 
    $p_id = (int)
    $p_id; 
    $func_num_args = func_num_args(); 
    $func_get_args = func_get_args(); 

    $result = mysql_query("SELECT task_name FROM tasks WHERE project_id = $p_id");
    while($project_tasks = mysql_fetch_assoc($result))
    {
        $html.= "<option value='".$project_tasks['task_name']."'>".$project_tasks['task_name']."</option>";
    }

    echo "<select name=\"process\">$html</select>";
}
$html = "";
foreach ($array as $key => $value){
    $html .= "<option value='$key'>$value</option>";
}
echo "<select name='process'>$html</select>";

= reassigns; .= appends

If you use = it reassigns $html in every iteration, so that $html will contain the result of the last iteration - one single option.

You need to concat the strings. Start by initializing $html to an empty string before starting your for loop.

$html = '';
foreach($array as $key => $value)
{
    $html .= "<option value='$key'>$value</key>";
    // same as $html = $html . "<option value='$key'>$value</key>";
}

Note: There is also a typo in your code:

echo "<select name="process">$html</select>";

should either be:

echo "<select name=\"process\">$html</select>";

OR

echo "<select name='process'>$html</select>";

if that's what you meant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM