改善动态选择下拉的加载时间

I'm creating some select drop downs dynamically with PHP.

<select name="player_id" style="width:140px;">
<?php usort($players, 'compareName'); ?>    
<?php foreach ($players as $player) { ?>
    <option value="<?php echo $player['id']; ?>"><?php echo $player['first_name'] . " " . $player['last_name']; ?></option>
<?php } ?>
</select>

The $players array currently has about 1600 records. The select drop down is created about 20 times, meaning it loops through the 1600 records 20 times.

My question is about load times.. is there a way I can create the same select once and then output it over and over again to improve load time rather than having it loop each time? Or would this be considered best practice?

Sure! You can load it once, save it in a variable and echo it wherever needed!

You can do it as follows:

<?php

$long_options_list = "";
usort($players, 'compareName');

foreach ($players as $player) { 
    $long_options_list .= '<option value="'.$player['id'].'">'. $player['first_name'] . " " . $player['last_name'].'</option>';
}

?>

Using it as follows:

<select name="player_id" style="width:140px;">
    <?php echo $long_options_list; ?>
</select>

Regarding the sorting, if you use it only once the usort won't impact your performances that much, but to use a ORDER BY in your query is surely the best choice!

To give you some code to illustrate how to save the output of your dynamic html, try out something like this:

<?php
//ignore this, I'm just generating some players as an example.
$players = array();
for ($i=0; $i < 1600 ; $i++) { 
    $players[] = array("first_name" => uniqid(), "last_name" => uniqid(), "id" => $i);
}

ob_start();
?>
<select name="player_id" style="width:140px;">
<?php usort($players, 'compareName'); ?>    
<?php foreach ($players as $player) { ?>
    <option value="<?php echo $player['id']; ?>"><?php echo $player['first_name'] . " " . $player['last_name']; ?></option>
<?php } ?>
</select>

<?php
$list = ob_get_clean();

echo $list;

echo $list;
?>

Also, if it's performance you're trying to figure out, using a database instead of usort order them for you will help a bit as well. So long as the way you're comparing them can be done by your database and it is properly indexed.

If the players are on a DB, then use ORDER BY when you SELECT them to let the DB engine order them for you.

Add an index to speed things up. Even with that amount of players, engines have ways of caching information in memory, so you will notice an improvement from your current situation.

Hope this helps.