首页 > 解决方案 > PHP计数变量和重定向

问题描述

我一直在摸索实现这一目标的最佳方法。

我从一个 url 得到 8 个变量: a=imagine b=lead c=champion d=champion e=champion f=champion g=lead h=champion

在这个例子中,有 5 个“冠军”,所以我会重定向到我的冠军页面。

我已将它们添加到数组中:

$a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $d = $_GET["d"]; $e = $_GET["e"]; $r = $_GET["r"]; $g = $_GET["g"]; $h = $_GET["h"];

$info = array($a,$b,$c,$d,$e,$f,$g,$h); print_r(array_count_values($info));

然后打印: Array ( [imagine] => 1 [lead] => 2 [cham​​pion] => 5 )

我做对了吗?我如何使用这些值重定向到我的冠军页面,因为这是最高计数?

标签: phparrays

解决方案


如果我理解正确:

$list = ['imagine' => 1 ,'lead' => 2, 'champion' => 5 ];

// find the highest count
$highest = max($list);

// check what page it is
foreach($list as $page=>$count){

    // redirect
    if($count === $highest){
        header('Location: ' . $page);
        exit();
    }
    
}

请注意,依赖用户输入是不安全的。我还会查找页面的白名单。


推荐阅读