MENU

PHP实现平滑加权轮询算法

August 28, 2021 • 接口

// $config 权重配置
// $appoint 第n次请求
function swrrb(array $config, int $appoint){
    $all_weight = array_sum(array_column($config,'weight')); // 所有权重总和
    if ($appoint > $all_weight) { // 如果取的次数大于权重总和
        $appoint = $appoint % $all_weight;
    }
    $max_index = 0;
    $back = [];
    for ($i = 1; $i <= $all_weight; $i++) {
        foreach ($config as $key => $value) {
            if(!isset($value['current'])){
                $config[$key]['current'] = 0;
            }
            $config[$key]['current'] += $config[$key]['weight'];
            if ($config[$key]['current'] > $config[$max_index]['current']) {
                $max_index = $key;
            }
        }
        $config[$max_index]['current'] -= $all_weight;
        if ($i === $appoint) {
            $back = $config[$max_index];
            break;
        }
    }
    return $back;
}

swrrb([
        [
            'name'=>'a',
            'weight'=>5
        ],
        [
            'name'=>'b',
            'weight'=>3
        ],
        [
            'name'=>'c',
            'weight'=>7
        ],
        [
            'name'=>'d',
            'weight'=>5
        ],
    ],31);