简体   繁体   English

基于重量的PHP重定向URL

[英]PHP Redirect URL based on weight

So I have an application that allows my client to enter in different url's and assign as many as he wants to a specific rotator as long as the weight always totals 100. 因此,我有一个应用程序,允许我的客户输入不同的url,并将其想要分配的数量分配给特定的旋转器,只要权重始终为100。

There is a link we give out to clients that when clicked on should fire a script that pulls the url and weight of that specific rotator and then redirect the end user to one of the url's assigned based on what weight it has. 我们提供给客户一个链接,单击该链接时应触发一个脚本,该脚本提取该特定旋转器的网址和权重,然后根据最终用户的权重将最终用户重定向到该网址的其中一个。

I'm struggling because the url's and weights are dynamic and can change at anytime. 我正在努力,因为网址和权重是动态的,并且可以随时更改。 I've seen a lot of examples but am still having an issue. 我看过很多例子,但仍然有问题。 If someone can please assist with this specific issue that would be fantastic. 如果有人可以协助解决这个特定的问题,那将是很棒的。

Thanks. 谢谢。

Here is my fast implementation: 这是我的快速实现:

<?php

$urls = array(
    array('url' => 'http://google.com', 'weight' => 50),
    array('url' => 'http://microsoft.com', 'weight' => 13),
    array('url' => 'http://apple.com', 'weight' => 42),
);

$total_weight = 0;
foreach ($urls as $url) {
    $total_weight += $url['weight'];
}

$rand = mt_rand(1, $total_weight);
var_dump($rand);

$selected_url = '';
foreach ($urls as $url) {
    $rand -= $url['weight'];

    if ($rand <= 0) {
        $selected_url = $url['url'];
        break;
    }
}

var_dump($selected_url);

Another one, a little more ellegant: 另一个,比较优雅:

<?php

$urls = array(
    array('url' => 'http://google.com', 'weight' => 50),
    array('url' => 'http://microsoft.com', 'weight' => 13),
    array('url' => 'http://apple.com', 'weight' => 42),
);

$probs = array();
foreach ($urls as $i => $url) {
    $probs = array_merge($probs, array_fill(1, $url['weight'], $i));
}

$rand = array_rand($probs);
var_dump($rand);
var_dump($urls[$probs[$rand]]['url']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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