php-yield生成器

奇葩也是花發表於2020-10-12
function createRange($number){
    for($i=0;$i<$number;$i++){
        yield time();
    }
}

$result = createRange(5); // 這裡呼叫上面我們建立的函式

var_dump($result);
foreach($result as $value){
    sleep(1);
    echo $value.'<br />';
}


//對某一陣列進行加權處理
$numbers = array('nike' => 200, 'jordan' => 500, 'adiads' => 800);

//通常方法,如果是百萬級別的訪問量,這種方法會佔用極大記憶體
function rand_weight($numbers)
{
    $total = 0;
    foreach ($numbers as $number => $weight) {
        $total += $weight;
        $distribution[$number] = $total;
    }
    $rand = mt_rand(0, $total-1);

    foreach ($distribution as $num => $weight) {
        if ($rand < $weight) return $num;
    }
}

//改用yield生成器
function mt_rand_weight($numbers) {
    $total = 0;
    foreach ($numbers as $number => $weight) {
        $total += $weight;
        yield $number => $total;
    }
}

function mt_rand_generator($numbers)
{
    $total = array_sum($numbers);
    $rand = mt_rand(0, $total -1);
    foreach (mt_rand_weight($numbers) as $num => $weight) {
        if ($rand < $weight) return $num;
    }
}

相關文章