dongqi4085 2014-07-09 17:00 采纳率: 0%
浏览 18
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • dongrao9454 2014-07-09 17:02
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?